Javascript 为什么在angular指令中多次调用ng类?

Javascript 为什么在angular指令中多次调用ng类?,javascript,html,angularjs,angularjs-directive,Javascript,Html,Angularjs,Angularjs Directive,我不知道为什么它被多次调用 <!doctype html> <html ng-app="HelloApp"> <body> <test-directive></test-directive> </body> </html> angular.module('HelloApp', []) .directive('testDirective', function () { return {

我不知道为什么它被多次调用

<!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>');
            }
        }
    }
});
以下是JSFIDLE:
打开链接并查看控制台。log

AngularJS编译DOM,以便它可以在幕后创建
div
并执行
ng类
。无论如何,
ng类
应该以另一种方式使用

当摘要循环运行时,您在AngularJS中使用的所有表达式都会得到多次求值。这是为脏检查完成的,脏检查验证表达式的当前值是否与上一个值不同

这意味着您不能依赖于在表达式中使用时调用方法的次数


请参阅“范围生命周期”一节,了解它是如何发生的

。我也发现了类似的问题
link
test 1
test 2
test 3