Angular.js programmatically setting a form field to dirty

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 will have to manually set $dirty to true and $pristine to false for the field. If you want the classes to appear on your input, then you will have to manually add ng-dirty and remove ng-pristine classes from the element. You can use $setDirty() on the form level to do all of this on the form itself, but not the form inputs, form inputs do not currently have $setDirty() as you mentioned.

This answer may change in the future as they should add $setDirty() to inputs, seems logical.


Since AngularJS 1.3.4 you can use $setDirty() on fields (source). For example, for each field with error and marked required you can do the following:

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});

Tags:

Angularjs