1

I am trying to get all the fields in a form and set them dirty.

Something like this :

 $timeout(function () {

        $('input').each(function(){

             $(this).$dirty=true;

        });
    }, 0);

This is not working. I do understand that something like this works just fine:

$scope.form.uName.$dirty = true;

But when I iterate through all the fields using jquery, something goes wrong.

Here is the fiddle: http://jsfiddle.net/Qdk5M/1302/

Appreciate any help. Thank you..

3 Answers 3

7

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

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});
Sign up to request clarification or add additional context in comments.

Comments

0

Create a directive with a link function that iterates through the form properties. Use a match to avoid any form object property which contains a $ to get to only the form fields. Set the $dirty property of these to true:

.directive('makeDirty', function(){
    return function(scope, elem, attr) {
        angular.forEach(scope.form, function(val, key){
            if(!key.match(/\$/)) {
                val.$dirty = true;
            }
        });
        scope.form.$setDirty(); // you can make the form itself $dirty if you wish to
    }
});

Updated Fiddle

The advantage of using a directive here is that it will not run the link code until the form is ready; with some minor refactoring, it could also be reused across multiple forms/controllers.

2 Comments

Thanks so much..this is exactly what I was looking for... one more question. I believe when you setdirty to the form it does not propagate to all the fields of the form.. is that true ?
Great - I'm glad. Yes, when you use $setDirty, the fields are unaffected. This is why I tacked it on at the end, after the code which sets $dirty on the individual fields.
0

Jquery elements and Angular form controllers are completely different things. Jquery elements does not have a $dirty property, the variables in form directive's controller's have that. You have to use the second script bit you posted.

1 Comment

Thanks for the insight... that makes total sense!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.