当我放入控制器
时出现此错误“ $ rootScope:infdig无限的$ digest循环”
控制器:
$scope.List = ["hello", "patrick", "daniel", " jemmy", "lara", "said", "charle", "ridha.", "radhi", "fred"
$scope.GetRandomListName = function() {
return $scope.List[Math.floor((Math.random() * List.lenght))];
}
];
CHTML:
<div class="row">
<blockquote>
{{GetRandomListName()}}
</blockquote>
</div>
答案 0 :(得分:0)
AngularJS不会一次调用<ul>
<li><a class="something" href="#">arrows</a></li>
</ul>
.something:active {
background-color: white;
}
,而是多次调用,直到结果相同为止。对于您而言,您将无法实现,因为函数每次都会生成随机数,因此会导致“ $ rootScope:infdig无限$ digest循环” 。因此,您应该GetRandomListName
的结果-为此,您还应该提供参数(cache
,因为可以有多个index
表达式,并且应该跟踪{{GetRandomListName}}
和相应的cache[index]
:
{{GetRandomListName(index)}}
angular.module('app', []).controller('ctrl', function($scope){
$scope.List = [];
for(var i = 0; i < 100; i++)
$scope.List.push(i);
var cache = [];
$scope.GetRandomListName = function(index) {
return cache[index]
|| (cache[index] = $scope.List[Math.floor((Math.random() * $scope.List.length))]);
}
})