1

I have trouble to set dynamic array key.

Here is my code,

HTML

<div ng-controller="myCtrl">
    <form ng-submit="sendPost()">
        <input ng-model="newName[12]"/>
        <button type="submit">Send</button>
    </form>
</div>

Controller

angular.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
    $scope.hello = {name: "Boaz"};
    $scope.newName = [];
    $scope.sendPost = function() {
            console.log($scope.newName);
    }                   
})

Expected Output

[12] => 13 (Input value)
[15] => 14 (Input value)

Que By setting dynamic input array key i can get empty key values.

Empty Object

Also you can check fiddle.

In this fiddle you can get empty object keys in console.

Thank you !

7
  • why are specifying 12 in ng-model="newName[12]"? Commented Dec 30, 2017 at 8:52
  • @OmarEinea It is my primary id for use it while update record. Commented Dec 30, 2017 at 8:53
  • 1
    why did you tag php? Commented Dec 30, 2017 at 8:54
  • @DhairyaLakhera okay i removed that Commented Dec 30, 2017 at 8:56
  • so what is your expected result? Commented Dec 30, 2017 at 8:56

1 Answer 1

2

If you only want the keys that have been set to exist in the data you send to your server, then use an object instead of an array. like so:

$scope.newName = {};

Instead of:

$scope.newName = [];

This way, what's sent to the server would be:

{
    12: "Input value",
    15: "Input value"
}

I hope this is what you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.