Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 834
hh54188 Avatar asked Aug 12 '15 13:08

hh54188


3 Answers

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.

like image 96
Rudra Avatar answered Nov 10 '22 18:11

Rudra


$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

like image 30
macrog Avatar answered Nov 10 '22 19:11

macrog


$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;
}
like image 33
Arno_Geismar Avatar answered Nov 10 '22 18:11

Arno_Geismar