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

…衆ロ難τιáo~ 提交于 2020-01-14 07:03:12

问题


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


回答1:


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




回答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



来源:https://stackoverflow.com/questions/20417407/why-ng-class-is-called-several-times-in-directive-of-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!