为什么NG-类是在角指令打过几次电话? [英] Why ng-class is called several times in directive of angular?

查看:114
本文介绍了为什么NG-类是在角指令打过几次电话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么它被称为几次。

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

下面是的jsfiddle: http://jsfiddle.net/yh9V5/
打开链接,看到的console.log

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

推荐答案

您在使用AngularJS所有前pression摘要周期运行时得到评估多次。这是为了脏检查这验证前pression的当前值是否是从最后一个值不同进行。

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.

这意味着你不能依靠如果前女友pression内使用的方法被调用的次数。

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-类是在角指令打过几次电话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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