javascript - $scope.$apply() 调用是否适合这种情况?

标签 javascript angularjs angularjs-scope angularjs-service angularjs-digest

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>

脚本.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 包装器(您可以将它注入(inject)到您的 DataStore 服务中),并且您不需要 $scope.$apply

关于javascript - $scope.$apply() 调用是否适合这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32526209/

相关文章:

javascript - 通过更改容器的宽度来对齐文本

使用 try .. catch .. finally 处理 Javascript 错误

angularjs - 无法在指令范围内访问 rootscope var

javascript - AngularJS $scope in 循环/forEach

javascript - Angular 4 jquery 不起作用

javascript - Meteor:如何循环遍历作为异步方法结果的数组

javascript - Angular js 观察 session 存储

javascript - AngularJS:范围监视未被触发,即使 objectEquality = true

javascript - 显示 API 返回的 PDF 文档

javascript - 无法理解 JavaScript 中的匿名函数语法