107

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.

5
  • may be you just need to set some (default) value? Aug 6, 2013 at 4:09
  • 3
    The $setDirty method is documented here: docs.angularjs.org/api/ng.directive:form.FormController
    – David Lin
    Aug 6, 2013 at 4:28
  • 2
    The seems to be on a form level. I need a $setDirty on a field level.
    – super9
    Aug 6, 2013 at 4:30
  • going on a limb here, but one possible, but rather hacky, solution to this would be to find out what event listener angular uses to bind to that type of field, and fire that listener manually immediately after the update. </uglyHack>
    – bguiz
    Aug 6, 2013 at 4:39
  • I was thinking of programmatically changing the class but it won't change the state of the form field in the correct manner I would have thought...
    – super9
    Aug 6, 2013 at 4:51

11 Answers 11

87

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.

3
  • This seemed to change for me between Angular 1.3.0-beta5 and 1.3.0, where 1.3.0 keeps the field $pristine as long as the $viewValue didn't change. I had to do $scope.myForm.myField.$pristine = false; $scope.myForm.myField.$setViewValue(...). Looks like the answer below stating that field.$setDirty() was added in Angular 1.3.4 will be the better solution
    – Johann
    Jan 28, 2015 at 0:12
  • 4
    Thanks for your note you saved my day " up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method " Jun 20, 2015 at 8:47
  • user rmag, and what about angular 2? Nov 13, 2016 at 12:12
51

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();
});
0
17

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.

1
  • 3
    $setPristine() is on input-field level but still no $setDirty in 1.2.26 :-(
    – Sebastian
    Oct 2, 2014 at 11:55
10

If you have access to the NgModelController (you can only get access to it from a directive) then you can call

ngModel.$setViewValue("your new view value");
// or to keep the view value the same and just change it to dirty
ngModel.$setViewValue(ngModel.$viewValue);
1
  • Thank you! Exactly what I was looking for.
    – dreyln
    Mar 12, 2014 at 19:13
10

Made a jsFiddle just for you that solves this issue. simply set $dirty to true, but with a $timeout 0 so it runs after DOM was loaded.

Find it here: JsFiddle

$timeout(function () {
  $scope.form.uName.$dirty = true;
}, 0);
0
7

This is what worked for me

$scope.form_name.field_name.$setDirty()
7

You can use $setDirty(); method. See documentation https://docs.angularjs.org/api/ng/type/form.FormController

Example:

$scope.myForm.$setDirty();
5

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;
}
3
  • Hey i unfortunately accidently downvoted this. How do I revert it. So telling me i cannot do this without answer being edited..
    – smk
    Feb 4, 2016 at 16:25
  • This works well; upvoting as checking for 'form.$error' ensures we are not 'dirtifying' fields the user did not touch, but which are valid.
    – Sam T
    Mar 28, 2016 at 15:38
  • Thank you! Easy and simple solution. Might not be the fastest but it doesn't do anything heavy so it really doesn't matter imo. Good work!
    – jwanglof
    Jan 25, 2017 at 8:48
4

Angular 2

For anyone looking to do the same in Angular 2 it is very similar apart from getting a hold of the form

<form role="form" [ngFormModel]="myFormModel" (ngSubmit)="onSubmit()" #myForm="ngForm">
<div class="form-group">
    <label for="name">Name</label>
    <input autofocus type="text" ngControl="usename" #name="ngForm" class="form-control" id="name" placeholder="Name">
    <div [hidden]="name.valid || name.pristine" class="alert alert-danger">
        Name is required
    </div>
</div>
</form>
<button type="submit" class="btn btn-primary" (click)="myForm.ngSubmit.emit()">Add</button>

import { Component, } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';

@Component({
    selector: 'my-example-form',
    templateUrl: 'app/my-example-form.component.html',
    directives: []
})
export class MyFormComponent {
    myFormModel: any;

    constructor(private _formBuilder: FormBuilder) {
        this.myFormModel = this._formBuilder.group({
            'username': ['', Validators.required],
            'password': ['', Validators.required]
        });
    }

    onSubmit() {
        this.myFormModel.markAsDirty();
        for (let control in this.myFormModel.controls) {
            this.myFormModel.controls[control].markAsDirty();
        };

        if (this.myFormModel.dirty && this.myFormModel.valid) {
            // My submit logic
        }
    }
}
3

Small additional note to @rmag's answer. If you have empty but required fields that you want to make dirty use this:

$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue !== undefined 
    ? $scope.myForm.username.$viewValue : '');
1
  • This is the answer that finally helped me! Jul 14, 2016 at 0:17
-1

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();
    }
}
1
  • 5
    Given that we're already using AngularJS, a jQuery solution seems overkill. Many people prefer to not use jQuery with AngularJS, for instance. Oct 31, 2014 at 21:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.