Why ng-class is called several times in directive of angular?
angularjs, angularjs-directive, html, javascript
Solution
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
Problem
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