我正在学习 AngularJs,但我无法让它工作。 我读过有关摘要循环的内容,但我不清楚。 很明显,这段代码失败了,因为进入了无限循环,但我不知道如何修复它。 有人可以帮助我吗?
<!DOCTYPE html>
<html lang="eng" ng-app="test">
<head>
<title>Learning Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.js"></script>
<script type="text/javascript">
var app = angular.module('test', ['ngRoute']);
app.factory('visitCounterService', function () {
var counterService = function() {
var _count = 1;
var counter = function() { return _count++; };
return { counter: counter }
}();
return counterService;
});
app.service('homeModel', ['visitCounterService', function(visitCounterService){
this.getTitle = function() {
var n = visitCounterService.counter();
return "Welcome to this awesome demo. You are the visitor n° " + n;
};
}]);
app.controller('homeController', ['$scope', 'homeModel', function($scope, homeModel) {
$scope.home = homeModel;
}]);
</script>
</head>
<body ng-controller="homeController">
<h3>{{home.getTitle()}}</h3>
</body>
</html>
感谢您的建议!!!
最佳答案
Angular 在 home.getTitle()
表达式上注册隐式 $watch。该表达式将至少被调用两次,因为 Angular 想要检查模型是否已稳定。
每次调用 home.getTitle()
时,您的代码都会返回不同的字符串,因此 Angular 会继续消化,直到达到最大消化循环限制。
尝试:
$scope.homeTitle = homeModel.getTitle();
和
<h3>{{homeTitle}}</h3>
关于javascript - infdig 无限 $digest 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23684711/