What's the differences between !$pristine vs $dirty in angularjs

All we need is an easy explanation of the problem, so here it is.

Recently I read some tutorial about angularJS form validation, like this:

<p ng-show="userForm.email.$invalid && !userForm.email.$pristine"></p>

but I think !$pristine and $dirty are equal, so can I use the below one instead?

<p ng-show="userForm.email.$invalid && userForm.email.$dirty"></p>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I think there is a slight difference between these two attributes, which depends on your use case.

$setDirty();
Sets the form to a dirty state.
This method can be called to add the ‘ng-dirty’ class and set the form to a dirty state (ng-dirty class). This method will also propagate to parent forms.

$setPristine();
Sets the form to its pristine state.
This method can be called to remove the ‘ng-dirty’ class and set the form to its pristine state (ng-pristine class). This method will also propagate to all the controls contained in this form.
Setting a form back to a pristine state is often useful when we want to ‘reuse’ a form after saving or resetting it.

So, you can use both $pristine and $dirty in a different way. Though, you can check the document as mentioned by ‘macrog’ in the below post.

Method 2

$pristine
boolean
True – if user has not interacted with the form yet.

$dirty
boolean
True – if user has already interacted with the form.

you can read all here

Method 3

$pristine: It will be TRUE, if the user has not interacted with the form yet

$dirty: It will be TRUE, if the user has already interacted with the form.

in essence !$pristine === $dirty

but you can use their respected css classes if you use them both.

In accordance with these AngularJS also provides corresponding CSS classes for them. We can use them for validation purpose.

ng-pristine
ng-dirty

Usage:

In Form: myForm.$dirty

For Field: myForm.fieldName.$dirty

In CSS:

.ng-dirty{
 background-color: yellow;
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply