Musical Shore
Musical Shore

Reputation: 1381

How do I bind an array to ngModel?

I am trying to bind a variable list of input elements to an array. Lets say I have an array

$scope.set = [{id: 1, value: 'foo'}, {id: 2, value: 'bar'}]

I would like to loop over that array and create an input element for each item.

<div ng-repeat="item in set">
  <input id="{{item_$index}}" ng-model="myModel.items[]"/>
</div>

I realize the above ng-model attribute is incorrect. What is the proper way to accomplish this requirement?

Upvotes: 0

Views: 155

Answers (3)

Frank van Wijk
Frank van Wijk

Reputation: 3252

You code looks good, but item_$index is undefined. If you want the index in the ng-repeat loop, use {{$index}}. See the ngRepeat docs for what 'magic' bindings you can use. Or just use item.id.

The ng-model can be anything of item. Do ng-model="item" or ng-model="item.value" for example. Since input has type="text" by default, item.value seems the most logical choice.

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136124

You need to use item.value in ng-model so that it can bind its value and that element item value will change when there is update.

Markup

<div ng-repeat="item in set">
  <input id="{{item.id}}" ng-model="item.value"/>
</div>

Upvotes: 4

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

Are you looking for something like this perhaps?

ng-model="item.value"

Upvotes: 1

Related Questions