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:
I'm not sure exactly why you're trying to mark the fields dirty, but I found myself in a similar situation because I wanted validation errors to show up when somebody attempted to submit an invalid form. I ended up using jQuery to remove the .ng-pristine
class tags and add .ng-dirty
class tags to the appropriate fields. For example:
$scope.submit = function() {
// `formName` is the value of the `name` attribute on your `form` tag
if (this.formName.$invalid)
{
$('.ng-invalid:not("form")').each(function() {
$(this).removeClass('ng-pristine').addClass('ng-dirty');
});
// the form element itself is index zero, so the first input is typically at index 1
$('.ng-invalid')[1].focus();
}
}
This is what worked for me
$scope.form_name.field_name.$setDirty()
A helper function to do the job:
function setDirtyForm(form) {
angular.forEach(form.$error, function(type) {
angular.forEach(type, function(field) {
field.$setDirty();
});
});
return form;
}
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
.
You can use $setDirty();
method. See documentation https://docs.angularjs.org/api/ng/type/form.FormController
Example:
$scope.myForm.$setDirty();