gpt4 book ai didi

javascript - angularjs ng-class 方法被多次调用

转载 作者:数据小太阳 更新时间:2023-10-29 04:13:54 24 4
gpt4 key购买 nike

在这个例子中,我有 2 个 ng-class,每个调用不同的 Controller 方法,由于某种原因每个方法被调用 3 次,知道吗?可能的错误?

var navList = angular.module('navList', []);

navList.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {
$scope.firstClass = function () {
console.log('firstClass');
return 'label label-success' ;
};
$scope.secondClass = function () {
console.log('secondClass');
return 'label' ;
};

}]);

http://jsfiddle.net/uDPHL/72/

谢谢

最佳答案

这不是错误。当 Angular 编译类似 ng-class="firstClass()" 的东西时,它会为它设置一个 $watch。摘要循环可能会多次评估每个 $watch:

Angular enters the $digest loop. The loop is made up of two smaller loops which process $evalAsync queue and the $watch list. The $digest loop keeps iterating until the model stabilizes, which means that the $evalAsync queue is empty and the $watch list does not detect any changes. -- Overview doc

还有

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. -- $watch docs

因此,至少需要两次。

关于javascript - angularjs ng-class 方法被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15951984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com