Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js programmatically setting a form field to dirty

Tags:

angularjs

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.

like image 253
super9 Avatar asked Aug 06 '13 04:08

super9


People also ask

How do you make angular forms dirty?

You should use the markAsDirty method, like this: control. markAsDirty(); This will also mark all direct ancestors as dirty to maintain the model.

What is dirty in angular form?

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"

What is $dirty in Angularjs?

$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.

What is $Setpristine in Angularjs?

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.


1 Answers

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.

like image 54
rmag Avatar answered Sep 19 '22 10:09

rmag