How to watch a jQuery selector using an AngularJS scope. $ Watch () Method

I am writing a directive that should keep track of elements that are updated with a specific class, for example .ng-invalid . As you know, .ng-invalid added to form elements that are invalid.

I need to look at these elements to determine if the class has been added or removed.

How can i achieve this?

Thank you in advance

+6
source share
2 answers

You can $ 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 . Enter two characters in this field to see the $ watch trigger.

+5
source

Is it enough for your purposes to watch the attribute $invalid FormController ? This will notify you of changes in the entire invalid form status, for example:

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

Source: https://habr.com/ru/post/943949/


All Articles