0

I have a simple form that displays the form with multiple inputs with the ability to remove those inputs.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
    $scope.numbers = [1,2,3];

    $scope.deleteField = function (number) {
      $scope.numbers.splice($scope.numbers.indexOf(number), 1);
    }
});

There is "required" validation on the elements:

  <form name="theForm">
      <div ng-repeat="number in numbers">
        <input type="text" name="number{{$index}}" ng-model="number" required/>
        <button ng-click="deleteField(number)">Delete</button>
        <span ng-show="theForm.number{{$index}}.$error.required">Number is required</span>
      </div>
  </form>

Validation works fine until I delete an entry. Once the deletion is done, the validation gets out of sync (the error messages get displayed on wrong fields or do not get displayed at all).

Here is the running example:

http://plnkr.co/edit/wF6c79xAwcZnPAxjf2bW?p=preview

1 Answer 1

2

Just add track by $index in your ng-repeat

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

2 Comments

Works a treat! Wondering why it's not a default behavior for ng-repeat but sure solves all the problems.
By default ng-repeat tracks by the whole content of each element, in your case the string (1,2,3), which also prevented you to have twice the same number in your array (as every item must have a unique tracking id). Tracking by $index solve that in your example, but would prevent updates if the array's items where objects instead of strings. Read more example and tutorials about ng-repeat if you want to know more.

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.