什么时候使用 $scope.$apply() 是安全的? [英] When is it safe to use $scope.$apply()?
问题描述
我想标题很清楚我在问什么.我创建了这个小提琴:http://jsfiddle.net/Sourabh_/HB7LU/13142/
在小提琴中,我试图复制一个 async
场景.这只是一个示例,但在 AJAX 调用中,如果我不使用 $scope.$apply()
列表不会更新.我想知道每次进行 AJAX 调用以更新列表时使用 $scope.$apply()
是否安全,或者是否有其他一些我可以使用的机制?
我为复制场景而编写的代码(与小提琴相同):
HTML
<li ng-repeat="项目中的项目">{{项目名称}}<button ng-click="change()">Change</button>
JS
var myApp = angular.module('myApp',[]);函数 MyCtrl($scope) {$scope.items = [{name : "abc"},{name : "xyz"},{name : "cde"}];$scope.change = function(){测试(功能(测试项目){$scope.items = testItem;//$scope.$apply();})}功能测试(回调){var testItem = [{名称:mno"},{名称:pqr"},{名称:ste"}];setTimeout(function(){callback(testItem)},2000);}}
如果您想模仿 API-Rest-Call,请在您的 Controller
中使用返回的 promise
而是在 Rest-Call 中设置范围.
$http.get('uri').成功(功能(数据){$scope.items = 数据});
避免使用 $apply()
.来自 Angular GitHub 存储库一个>:
$scope.$apply()
应该尽可能接近异步事件绑定可能.
不要在你的代码中随意散布它.如果你正在做(!$scope.$$phase) $scope.$apply()
那是因为你不够高在调用堆栈中.
针对您的问题:
- 如果您发现自己需要 $apply(),请重新考虑您的结构.
- 出于安全原因:切勿使用
$apply()
I guess the title is pretty much clear what I am asking. I have created this fiddle : http://jsfiddle.net/Sourabh_/HB7LU/13142/
In the fiddle I have tried to replicate an async
scenario. This is just an example but in an AJAX call if I don't use $scope.$apply()
the list does not get updated. I want to know if it is safe to use $scope.$apply()
every time I make an AJAX call to update a list or is there some other mechanism I can make use of?
Code I have written to replicate the scenario(same as in fiddle):
HTML
<div ng-controller="MyCtrl">
<li ng-repeat="item in items">
{{item.name}}
</li>
<button ng-click="change()">Change</button>
</div>
JS
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.items = [{name : "abc"},{name : "xyz"},{name : "cde"}];
$scope.change = function(){
test(function(testItem){
$scope.items = testItem;
//$scope.$apply();
})
}
function test(callback){
var testItem = [
{name : "mno"},
{name : "pqr"},
{name : "ste"}
];
setTimeout(function(){callback(testItem)},2000);
}
}
If you want to immidate an API-Rest-Call, use the returned promise
in your Controller
instead setting the scope inside the Rest-Call.
$http.get('uri')
.success(function(data) {
$scope.items = data
});
Avoid using $apply()
. From the Angular GitHub Repo:
$scope.$apply()
should occur as close to the async event binding as possible.Do NOT randomly sprinkle it throughout your code. If you are doing if
(!$scope.$$phase) $scope.$apply()
it's because you are not high enough in the call stack.
To your question:
- If you find yourself in a situation where you need $apply(), rethink your structure.
- Just for safety reason: Never use
$apply()
这篇关于什么时候使用 $scope.$apply() 是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!