javascript – 这个场景是$scope.$apply()调用吗?
作者:互联网
AngularJS(和坦率地说,JavaScript)的新功能,但是从我收集到的内容中,只有当更改发生在angular的雷达之外时,才需要显式调用$scope.$apply().下面的代码(粘贴自this plunker)让我觉得不需要调用它的情况,但这是我能让它工作的唯一方法.我应该采取不同的方法吗?
index.html的:
<html ng-app="repro">
<head>
...
</head>
<body class="container" ng-controller="pageController">
<table class="table table-hover table-bordered">
<tr class="table-header-row">
<td class="table-header">Name</td>
</tr>
<tr class="site-list-row" ng-repeat="link in siteList">
<td>{{link.name}}
<button class="btn btn-danger btn-xs action-button" ng-click="delete($index)">
<span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
</table>
</body>
</html>
的script.js:
var repro = angular.module('repro', []);
var DataStore = repro.service('DataStore', function() {
var siteList = [];
this.getSiteList = function(callback) {
siteList = [
{ name: 'One'},
{ name: 'Two'},
{ name: 'Three'}];
// Simulate the async delay
setTimeout(function() { callback(siteList); }, 2000);
}
this.deleteSite = function(index) {
if (siteList.length > index) {
siteList.splice(index, 1);
}
};
});
repro.controller('pageController', ['$scope', 'DataStore', function($scope, DataStore) {
DataStore.getSiteList(function(list) {
$scope.siteList = list; // This doesn't work
//$scope.$apply(function() { $scope.siteList = list; }); // This works
});
$scope.delete = function(index) {
DataStore.deleteSite(index);
};
}]);
解决方法:
setTimeout(function() { callback(siteList); }, 2000);
此行将带您进入Anglar的摘要循环之外.您可以简单地将setTimeout替换为Angular的$timeout包装器(您可以将它注入到DataStore服务中),并且您不需要$scope.$apply.
标签:javascript,angularjs,angularjs-service,angularjs-scope,angular-digest 来源: https://codeday.me/bug/20190611/1221661.html