How To Watch a JQuery Selector Using AngularJS scope.$watch() Method
angularjs, javascript, jquery
Solution
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.
Problem
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