admin 管理员组

文章数量: 1086019

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

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

Share Improve this question edited Apr 30, 2013 at 23:01 lucuma 18.3k4 gold badges67 silver badges95 bronze badges asked Apr 30, 2013 at 9:10 AbilashAbilash 6,0896 gold badges27 silver badges30 bronze badges 2
  • could you share your code with fiddle or plunker demo – Ajay Singh Beniwal Commented Apr 30, 2013 at 9:32
  • Here is a dummy fiddle for my requirement. jsfiddle/aW7FD – Abilash Commented Apr 30, 2013 at 11:19
Add a ment  | 

2 Answers 2

Reset to default 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.

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

本文标签: javascriptHow To Watch a JQuery Selector Using AngularJS scopewatch() MethodStack Overflow