angularjs中的ng样式为什么运行不正确



我有一个类似下图的ng样式ng型

为什么计数不显示3、4,而是显示22、23

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-style="countStyle()">Welcome {{count}}</h1>
<h1 ng-style="countStyle()">Welcome {{count}}</h1>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

$scope.myObj = {
"color" : "white",
"background-color" : "coral",
"font-size" : "60px",
"padding" : "50px"
}
var i = 2;
$scope.count = 1;
$scope.countStyle = function(){
i += 1;
$scope.count = i;
return $scope.myObj;
}
});
</script>
</body>
</html>

在此处输入图像描述

22(2+20(

这是因为您下面的每个代码都将达到摘要循环阈值的限制,即10:

<h1 ng-style="countStyle()">Welcome {{count}}</h1>
<h1 ng-style="countStyle()">Welcome {{count}}</h1>

因为上面有2个绑定,所以它将运行摘要循环20次并中止。

试着删除上面的一行,比如:

<h1 ng-style="countStyle()">Welcome {{count}}</h1>

然后它将显示12。(2+10(

演示

这是因为您的方法在每个摘要周期都会被调用,请尝试在$scope.countStyle方法中添加console.log。

它将抛出一个名为:angular.min.js:124的错误:[$rootScope:infdig]

这意味着达到了10个$digest((迭代。

最新更新