alexs333
alexs333

Reputation: 12593

AngularJS validation gets out of sync when removing a form element

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

Upvotes: 0

Views: 288

Answers (1)

floribon
floribon

Reputation: 19193

Just add track by $index in your ng-repeat

Upvotes: 2

Related Questions