Reputation: 4568
How do I bind an ng-model that is an array to a fixed number of textboxes?
Let's say I have three textboxes and they are all optional, how do you bind the ng-model to those textboxes?
<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">
You can type into any textbox (e.g. textboxes 2 and 3 only) and when you save it, it's just going to be optionalField: ['text2', 'text3']
.
Where you place the text doesn't matter; what matters is the order of the textboxes. So when you show the view again, it's just going to be bound to the first and second textboxes. If you only typed on the textbox 3, it will be bound to textbox 1 and so on.
UPDATE:
Just used dfsq's answer and modified it to return a filtered array of values. http://codepen.io/anon/pen/ozpxGq?editors=1011
Upvotes: 2
Views: 550
Reputation: 6628
In ng-repeat
you can use $index
<input type="text" name="optionalField[]" ng-model="optionalField[$index]">
Upvotes: 2
Reputation: 193261
Like this:
<input type="text" name="optionalField[]" ng-model="optionalField[0]">
<input type="text" name="optionalField[]" ng-model="optionalField[1]">
<input type="text" name="optionalField[]" ng-model="optionalField[2]">
Upvotes: 0