AngularJS ng-repeat and form validation

I am having trouble validating a form in AngularJS and using ng-repeating elements inside a form.

HTML:

<div ng-app> <div ng-controller="EditController"> <form name="form" novalidate>Name: <br/> <input type="text" ng-model="model.name" required="" /> <hr />Products: <br/> <div ng-repeat="product in model.products"> <div> <input type="text" ng-model="product.name" required="" /> <input type="text" ng-model="product.price" required="" /> <a href="javascript:void(0)" ng-click="remove($index)">Remove</a> </div> </div> <hr /> <button ng-disabled="form.$invalid || !form.$dirty" ng-click="save()">save</button> <div ng-show="form.$invalid && !form.$pristine">There are errors.</div> <div ng-show="!form.$dirty && form.$pristine">No changed detected to be saved.</div> <div> <p>Dirty? {{form.$dirty}}</p> <p>Invalid? {{form.$invalid}}</p> <p>Pristine? {{form.$pristine}}</p> </div> </form> </div> </div> 

JS:

 function EditController($scope) { $scope.model = { name: "Phil", products: [{ name: "Foo", price: 12.99 }, { name: "Bar", price: 15.99 }, { name: "FooBar", price: 24.99 }] }; $scope.remove = function(index){ $scope.model.products.splice(index, 1); }; $scope.save = function () { console.log("saved"); }; } 

Violin:

http://jsfiddle.net/66V6m/2/

Replication:

Remove 1 element by clicking remove, the form will not become dirty so that the button does not turn on.

If you change the name field, the form will then become dirty.

Any ideas on how to remove an element from an array make this form dirty?

+7
source share
2 answers

Angular provides the $setDirty() function only for the purpose you are trying to accomplish here. Just add it to your ng-click attribute, for example:

 <input type="text" ng-model="product.price" required="" /> <a href="javascript:void(0)" ng-click="remove($index); form.$setDirty(true);">Remove</a> 

I split your violin and work here

+11
source

Here is one way.

 $scope.remove = function (index) { $scope.model.products.splice(index, 1); $scope.form.$dirty = true; }; 
+2
source

All Articles