8

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

Philly guy
  • 135
  • 2
  • 6
  • If your goal is to have conditional classes for your labels, have a look at this SO post: http://stackoverflow.com/a/15664427/1036025 – jpmorin Apr 11 '13 at 17:01

1 Answers1

7

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.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492