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>
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.
$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
$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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With