Abilash
Abilash

Reputation: 6089

How To Watch a JQuery Selector Using AngularJS scope.$watch() Method

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

Upvotes: 6

Views: 4713

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364747

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.

Upvotes: 6

Ezekiel Victor
Ezekiel Victor

Reputation: 3876

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) {
  // ...
});

Upvotes: 1

Related Questions