Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs ng-class method is getting invoked multiple times

In this example, i got 2 ng-class, each calling different controller method, for some reason each method get called 3 times, Any idea? Possible bug?

var navList = angular.module('navList', []);

navList.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {
    $scope.firstClass = function () {
        console.log('firstClass');
        return 'label label-success' ;
    };     
    $scope.secondClass = function () {
        console.log('secondClass');
        return 'label' ;
    };     

}]);

http://jsfiddle.net/uDPHL/72/

Thanks

like image 923
Philly guy Avatar asked Apr 11 '13 14:04

Philly guy


1 Answers

It is not a bug. When Angular compiles something like ng-class="firstClass()", it sets up a $watch for it. A digest loop may evaluate each $watch multiple times:

Angular enters the $digest loop. The loop is made up of two smaller loops which process $evalAsync queue and the $watch list. The $digest loop keeps iterating until the model stabilizes, which means that the $evalAsync queue is empty and the $watch list does not detect any changes. -- Overview doc

Also

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. -- $watch docs

So, at least two times is expected.

like image 52
Mark Rajcok Avatar answered Nov 07 '22 17:11

Mark Rajcok