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
You can use getter function or get accessor to act as watch on angular 2.
In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever $apply() is called to update the data bindings.
The $scope. $apply() function is used to execute some code, and then call $scope. $digest() after that, so all watches are checked and the corresponding watch listener functions are called. The $apply() function is useful when integrating AngularJS with other code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With