$ scope.$ apply()调用是否适用于此方案?

Gus*_*usP 4 javascript angularjs angularjs-service angularjs-scope angularjs-digest

AngularJS(和坦率地说,JavaScript)的新功能,但是从我收集到的内容中,只有当更改发生在angular的雷达之外时,才需要显式调用$ scope.$ apply().下面的代码(从这个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>
Run Code Online (Sandbox Code Playgroud)

的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);
  };
}]);
Run Code Online (Sandbox Code Playgroud)

pab*_*han 5

setTimeout(function() { callback(siteList); }, 2000);
Run Code Online (Sandbox Code Playgroud)

此行将带您进入Anglar的摘要循环之外.你可以简单地setTimeout用Angular的$timeout包装器替换(你可以将它注入到你的DataStore服务中),而你也不需要$scope.$apply.