In AngularJS, what's the difference between ng-pristine and ng-dirty?

The ng-dirty class tells you that the form has been modified by the user, whereas the ng-pristine class tells you that the form has not been modified by the user. So ng-dirty and ng-pristine are two sides of the same story.

The classes are set on any field, while the form has two properties, $dirty and $pristine.

You can use the $scope.form.$setPristine() function to reset a form to pristine state (please note that this is an AngularJS 1.1.x feature).

If you want a $scope.form.$setPristine()-ish behavior even in 1.0.x branch of AngularJS, you need to roll your own solution (some pretty good ones can be found here). Basically, this means iterating over all form fields and setting their $dirty flag to false.

Hope this helps.


pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<form ng-app="" name="myForm">
  <input name="email" ng-model="data.email">
  <div class="info" ng-show="myForm.email.$pristine">
    Email is virgine.
  </div>
  <div class="error" ng-show="myForm.email.$dirty">
    E-mail is dirty
  </div>
</form>

A field that has registred a single keydown event is no more virgin (no more pristine) and is therefore dirty for ever.


Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

Tags:

Angularjs