Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 736
Abilash Avatar asked Apr 30 '13 09:04

Abilash


People also ask

What is the angular equivalent to an AngularJS $Watch?

You can use getter function or get accessor to act as watch on angular 2.

What is $apply in AngularJS?

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.

What is scope apply?

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.


1 Answers

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.

like image 65
Mark Rajcok Avatar answered Sep 22 '22 05:09

Mark Rajcok