Angular $ setPristine () not working

I am trying to use the built-in functions of an Angular form, in particular setPristine() , to clear the form from the submit user. My controller has access to $scope.newForm (my form) with all its methods, but running $scope.newForm.$setPristine() does not reset the form fields.

Here is my HTML:

 <div ng-controller="NewFormController"> <h3>New Entry</h3> <form name="newForm" method="post" novalidate> <div class="input-group"> <label>Name</label> <input name="name" type="text" ng-model="place.name"/> </div> <div class="input-group"> <label>Description</label> <textarea name="description" type="text" ng-model="place.description"></textarea> </div> <div class="input-group"> <label>Neighborhood</label> <input name="neighborhood" type="text" ng-model="place.neighborhood"/> </div> <div class="input-group"> <label>Address</label> <input name="location" type="text" ng-model="place.address"/> </div> <input type="submit" value="Submit" ng-click="submit(place)"/> </form> </div> 

And here is the controller where I call setPristine() :

 app.controller('NewFormController', function($scope, $compile) { $scope.place = { name: 'ExamplePlace', description: 'This is a description!', neighborhood: 'Manhattan', address: '112 Street Place' }; $scope.submit = function(place) { $scope.newForm.$setPristine(); $scope.newForm.$setUntouched(); }; }); 

Here is the working code that reproduces my problem.

Note. I am using Angular version 1.4.3.

+5
source share
1 answer

$setPristine only marks the form as $pristine , which is useful for test expressions and CSS (e.g. .ng-dirty )

So $setPristine does not clear form controls. In fact, he did not even know how to do it. Think that β€œclean” can mean different things for different models. "Clear" can mean "" , or undefined , or null , or anything at all, which could mean that a user input control that works with ngModel .

So, in order to properly clean the form, you need to change the viewing model that controls the form, any definition of "clear" that is required. In most cases - including yours - it's just a matter of having the View Model installed on a new object:

 $scope.submit = function(place) { $scope.newForm.$setPristine(); $scope.newForm.$setUntouched(); // clear the form $scope.place = {}; }; 
+11
source

All Articles