6

I'm writing a directive which needs to watch for elements that get updated with a particular class, say .ng-invalid. As you know, .ng-invalid is added to form elements which are invalid.

I need to watch these elements to determine if the class was added or removed.

How can I achieve this?

Thanks in advance

2
  • could you share your code with fiddle or plunker demo Commented Apr 30, 2013 at 9:32
  • Here is a dummy fiddle for my requirement. jsfiddle.net/aW7FD Commented Apr 30, 2013 at 11:19

2 Answers 2

6

You could $watch a function that gets the length of $(".ng-invalid"):

scope.$watch(function() {
    return $(".ng-invalid").length;
}, function (newVal, oldVal) {
    if(newVal !== oldVal) {
       console.log('changed!', newVal, oldVal);
       // do your changes here
    }
})

Fiddle. In the fiddle, I added ng-minlength="2" to the first input. Type two characters into that field to see the $watch trigger.

Sign up to request clarification or add additional context in comments.

1 Comment

This is really elegant! Worked like a charm :D
1

Would it be sufficient for your purposes to watch the $invalid attribute of FormController? This will notify you of changes to the form's holistic invalid status, for example:

// Somewhere in your directive; formCtrl is the FormController
scope.$watch(function() {
  return formCtrl.$invalid;
}, function(isInvalid, wasInvalid) {
  // ...
});

1 Comment

No this is not sufficient for my requirement :-(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.