为什么 ng-class 在 angular 指令中被多次调用? [英] Why ng-class is called several times in directive of angular?

查看:29
本文介绍了为什么 ng-class 在 angular 指令中被多次调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>');
            }
        }
    }
});

控制台结果是

link
test 1
test 2
test 3

这里是 JSFIDDLE:http://jsfiddle.net/yh9V5/打开链接,看到console.log

Here is JSFIDDLE : http://jsfiddle.net/yh9V5/ Open the link and see the console.log

推荐答案

当摘要循环运行时,您在 AngularJS 中使用的所有表达式都会被多次评估.这样做是为了验证表达式的当前值是否与上一个值不同的脏检查.

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.

请参阅范围生命周期"部分以了解它是如何发生的http://docs.angularjs.org/guide/scope

See the section "Scope Life cycle" to understand how it happens http://docs.angularjs.org/guide/scope

这篇关于为什么 ng-class 在 angular 指令中被多次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆