gpt4 book ai didi

javascript - infdig 无限 $digest 循环

转载 作者:行者123 更新时间:2023-11-28 13:32:40 27 4
gpt4 key购买 nike

我正在学习 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/

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