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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With