15

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

Dai-Hyun Lim
  • 209
  • 2
  • 7
  • Thanks guys. I also found similar issue which is http://stackoverflow.com/questions/9682092/databinding-in-angularjs – Dai-Hyun Lim Dec 06 '13 at 08:26

2 Answers2

8

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

Chandermani
  • 42,589
  • 12
  • 85
  • 88
2

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

mdolbin
  • 936
  • 4
  • 8