无限循环带角的前pression结合
我有一个显示通过一个简单的前pression结合由控制器方法返回的值的角度应用程序:
I have an angular application that displays the value returned by a controller method through a simple expression binding:
<div>{{getValue()}}</div>
如果有问题的方法只返回一个值,该方法被调用了两次,那就是自叹不如:
If the method in question just returns a value, the method is called twice, and that is strange enough:
$scope.getValue = function(){
return 'some value';
}
但是,如果方法做一些异步工作方式,如从服务器获取文件时,code进入一个无限循环:
But if the method does some asynchronous work such as getting a file from the server, the code goes into an infinite loop:
$scope.getValueAsync = function(){
$http.get('myfile.html')
.success(function (data, status, headers, config) {
return 'some async value';
});
return 'file not found'; // same value returned every time but $digest cycle still loops
}
我是新来的角等等都可能错过了一些基本的东西在这里,但有人可以请解释这是怎么回事?
I'm new to Angular so have probably missed something basic here, but can someone please explain what is going on?
Plunker
下面是一个plunker与 http://plnkr.co/7BriYDbdVJvIoIigQcTU
Here's a plunker to play with http://plnkr.co/7BriYDbdVJvIoIigQcTU
即使你的异步函数每次都返回相同的确切字符串中,$消化周期循环中解雇了,因为你的函数也使得以$ HTTP调用Ajax服务
Even though your async function returns the same exact string every time, the $digest cycle is fired in loops because your function also makes an ajax call with $http service.
$ http服务触发器 $ rootScope。$适用()
的当请求已完成并自 $适用
触发$消化周期它使你的看法前pression进行重新评估,这反过来导致你的异步函数再次调用,等等...
$http service triggers $rootScope.$apply()
when requests are completed and since $apply
triggers a $digest cycle it makes your view expression to be re-evaluated, which in return causes your async function to be called again, and so on...
app.controller('MainCtrl', function($scope, $http) {
$scope.getValue = function(){
return 'some value';
}
$scope.getValueAsync = function(){
$http.get('myfile.html')
.success(function (data, status, headers, config) {
return 'some async value';
});
return 'file not found';
}
});
<div>{{getValueAsync()}}</div>
这个故事告诉我们:如果您在EX pressions使用的功能,请确保您的功能并不影响他们之外的东西会引发消化$循环,并确保您的函数总是返回相同的输出给定相同的输入。
Moral of the story: If you use functions in expressions, make sure your functions don't affect something outside of them that would trigger a $digest loop, and make sure your functions always return the same output given the same input.