Angular $setPristine() not working

I'm trying to use Angular's built-in form functions, specifically setPristine() to clear the form on user submit. My controller has access to $scope.newForm (my form) with all of its methods, but running $scope.newForm.$setPristine() isn't resetting 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 a working codepen that reproduces my problem.

Note: I'm using Angular version 1.4.3.

Answers:

Answer

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

So, $setPristine does not clear the form's controls. In fact, it wouldn't even know how to do that. Consider, that to "clear" could mean different things to different models. "Clear" could mean "", or undefined, or null, or anything at all that a custom input control that works with ngModel could mean.

So, to properly clear the form is to modify the View Model that drives the form to whatever definition of "clear" it needs. In most cases - yours included - it is just a matter of setting the View Model to a new object:

$scope.submit = function(place) {
   $scope.newForm.$setPristine();
   $scope.newForm.$setUntouched();

   // clear the form
   $scope.place = {};
};

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.