0

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:

  1. Click "Add Phase". A new row will appear with a blank value
  2. Select something in the new row
  3. Click "Add Phase" again.

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!

1 Answer 1

2

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]'>

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

2 Comments

Interesting. I incorrectly assumed the "phase in phases..." would mean I could use "phase" as the loop variable, kind of like "for (String s : allStrings)...". Thank you so much for your answer!
I this I was wrong on the reason. What I actually think is that "phase" was a temporary reference in the ng-repeat, when the scope got refreshed the reference got lost, but that still doesn't explain why the first two never changed.

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.