Add*_*son 8 javascript infinite-loop angularjs
我正在一个可以搜索食物的网站上工作,看看它是水果,蔬菜还是两种(因为我很无聊).我决定使用Angular,尽管我很陌生.我开始收到此错误:$ rootScope:infdig Infinite $ digest循环
这可能是也可能不是确切的措辞或错误,因为页面滞后这么多,我无法打开Javascript控制台.
这是我的结果视图控制器:
app.controller('resultController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$scope.result = $routeParams.query;
$scope.whatIsIt = function() {
$http.get('json/foods.json').success(function(data) {
var lists = JSON.parse(data);
var itIsA = 'uuggghhhhh';
if (lists['fruit'].contains($scope.result)) {
itIsA = 'fruit';
} else if (lists['vegetable'].contains($scope.result)) {
itIsA = 'vegetable';
}
});
}
}]);
Run Code Online (Sandbox Code Playgroud)
继承我的app模块:
var app = angular.module('fruitOrNot', [
'ngRoute'
]);
app.config(['$routeProvider' ,
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'layouts/fruit-search.html',
controller: 'searchController'
}).when('/:query', {
templateUrl: 'layouts/result.html',
controller: 'resultController'
});
}]);
Run Code Online (Sandbox Code Playgroud)
这是layouts/result.html:
<h1>{{ result }}</h1>
<p>{{ result }} is a {{ whatIsIt() }}</p>
Run Code Online (Sandbox Code Playgroud)
所以我想知道是什么原因可能导致$digest循环错误,或者如何查找,因为我无法使用控制台.谢谢!
整个项目也在 Github上.
您遇到的问题是您在范围上设置一个字段,该字段隐式调用$digest并再次布置模板。但是,布局模板会再次发出 http 请求,然后更改范围,这会调用 $digest。这就是无限循环。
您可以通过确保在模板布局期间永远不会触发 http 请求来避免这种情况。
实现应用程序的一种更有角度的正确方法是将 GET 请求提取到适当的服务中,然后将服务注入到控制器中。
然后在控制器中进行服务调用,如下所示:
app.controller('resultController', ['$scope', '$routeParams', 'whatsitService',
function($scope, $routeParams, $http) {
$scope.result = $routeParams.query;
whatsitService.doit().then(function(result) {
$scope.whatsit = result;
}
})
;
Run Code Online (Sandbox Code Playgroud)
您的模板将如下所示:
<h1>{{ result }}</h1>
<p>{{ result }} is a {{ whatsit }}</p>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14437 次 |
| 最近记录: |