I am programmatically updating some of the fields on my form with a value and I would like to set the field state to $dirty
. Doing something like:
$scope.myForm.username.$dirty = true;
doesn't seem to work.
There is a method $setPristine
that I can use to reset the state of the field but there isn't a $setDirty
method?
So how does one go about doing this?
I saw this post https://groups.google.com/forum/#!topic/angular/NQKGAFlsln4 but I can't seem to find the $setDirty
method. I am using Angular version 1.1.5.
You should use the markAsDirty method, like this: control. markAsDirty(); This will also mark all direct ancestors as dirty to maintain the model.
When the user changes the value in the watched field, the control is marked as "dirty" When the user blurs the form control element, the control is marked as "touched"
$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.
Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false.
In your case, $scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue);
does the trick - it makes both the form and the field dirty, and appends appropriate CSS classes.
Just to be honest, I found this solution in new post in the topic from the link from your question. It worked perfectly for me, so I am putting this here as a standalone answer to make it easier to be found.
EDIT:
Above solution works best for Angular version up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method $setDirty()
from ngModel.NgModelController
.
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