我想这个标题非常清楚我要问的是什么.我创造了这个小提琴:http://jsfiddle.net/Sourabh_/HB7LU/13142/
在小提琴中,我试图复制一个async场景.这只是一个例子,但在AJAX调用中如果我不使用$scope.$apply()该列表则不会更新.我想知道$scope.$apply()每次进行AJAX调用更新列表时是否安全使用,还是有其他一些我可以使用的机制?
我编写的代码用于复制场景(与小提琴相同):
HTML
<div ng-controller="MyCtrl">
<li ng-repeat="item in items">
{{item.name}}
</li>
<button ng-click="change()">Change</button>
</div>
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)