Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ng-class is called several times in directive of angular? [duplicate]

I don't know why it is called several times.

<!doctype html>
<html ng-app="HelloApp">
<body>
  <test-directive></test-directive>
</body>
</html>

angular.module('HelloApp', [])
.directive('testDirective', function () {
    return {
        restrict: 'E',
        replacement: true,
        template: '<div ng-class="test()">Test Directive</div>',
        link : function (scope, element, attrs) {
            console.log('link');
            var cnt = 0;
            scope.test = function () {
                cnt += 1;
                console.log('test', cnt);
                //element.append('<h6>test' + cnt + '</h6>');
            }
        }
    }
});

the console result is

link
test 1
test 2
test 3

Here is JSFIDDLE : http://jsfiddle.net/yh9V5/ Open the link and see the console.log

like image 989
Dai-Hyun Lim Avatar asked Dec 06 '13 06:12

Dai-Hyun Lim


2 Answers

All expression that you use in AngularJS get evaluated multiple times when a digest cycle runs. This is done for dirty checking which validates whether the current value of expression is different from the last value.

This means you cannot rely on how many times a method gets called if used within an expression.

See the section "Scope Life cycle" to understand how it happens http://docs.angularjs.org/guide/scope

like image 149
Chandermani Avatar answered Nov 15 '22 22:11

Chandermani


AngularJS compiles DOM so it might create div and execute ng-class few times behind the scenes. Anyways, ng-class is expected to be used in another way http://docs.angularjs.org/api/ng.directive:ngClass

like image 2
mdolbin Avatar answered Nov 15 '22 20:11

mdolbin