Reputation: 55
I have a problem dynamically adding items to an array that serves as the model for an ng-repeat.
The plunker is here: http://plnkr.co/edit/W4b34EDR8dP7ems7aFRV?p=preview
I have a list of table rows. In each row is a select box whose contents are the same for each row. The ng-model for the select is simply the string that acts as the item in the first ng-repeat (it's harder to explain than it is to just look at the plunker!)
My problem is when I click the button to add a row. Follow these steps:
The new row is added, but the selection is cleared from the 3rd row. Why is this happening and how do I avoid it? I've tried to google of course, but it's a hard problem to find words to google on.
Here's some code:
<tr ng-repeat="phase in phases track by $index">
<td>{{$index + 1}}</td>
<td><select ng-model='phase'>
<option ng-repeat="item in availablePhases" ng-value="item">{{item}}</option>
</select>
</td>
</tr>
And the controller:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.phases = ['Phase 1', 'Phase 2'];
$scope.availablePhases = ['Phase 0', 'Phase 1', 'Phase 2', 'Phase 3'];
$scope.add = function() {
$scope.phases.push('');
}
});
Thanks!
Upvotes: 0
Views: 1389
Reputation: 3831
You are giving all the values the same model
, so when you updated one you updated them all. I am not sure why it didn't change the first two. To get it working just change
<select ng-model='phase'>
to
<select ng-model='phases[$index]'>
Upvotes: 2