【问题标题】:AngularJS - Change TrackingAngularJS - 更改跟踪
【发布时间】:2013-11-17 14:11:21
【问题描述】:

我是 AngularJS 的新手。我正在考虑使用$timeout 服务。我已经读到,在 JavaScript setTimeout 函数上使用 $timeout 的原因之一是因为在调用 $scope.$apply 之前,对 $scope 中变量的更改不会在 UI 中更新。虽然就是这个词,但我无法用实际代码确认这一点。我写了以下内容:

index.html

<div ng-app="myApp">
  <div ng-controller="myController">
    <div>AngularJS Count: {{total1}}</div>
    <br />

    <div>setTimeout Count: {{total2}}</div>
    <br />

    <button ng-click="start()">start</button>
  </div>
</div>

myController.js

var app = angular.module("myApp", []);
function myController($scope, $timeout) {
  $scope.total1 = 0;
  $scope.total2 = 0;

  $scope.isStarted = false;
  $scope.toggle = function() {
    if (!$scope.isStarted) {
      $scope.isStarted = true;

      $timeout(ngUpdate, 1000);      
      setTimeout(jsUpdate, 1000);
    }    
  };  

  function ngUpdate() {
      $scope.total1 = $scope.total1 + 1;
  }

  function jsUpdate() {
      $scope.total2 = $scope.total2 + 1;
  }
}

在此代码示例中,对 $scope 上的变量所做的更改会在 UI 中更新。我试图在代码中看到一个场景,其中通过 setTimeout 函数进行的更改在调用 $scope.$apply 之前不会更新 UI。我是不是误会了?或者是对 AngularJS 框架进行了更改,导致原始断言过时。

【问题讨论】:

  • 对不起,我的例子错了。我将对其进行更多研究并再次回答:)

标签: angularjs settimeout angularjs-timeout


【解决方案1】:

由于您是从$scope.toggle 内部调用setTimeout,因此该代码已经在$digest 循环的上下文中执行。因此,无需致电$apply

$timeout 将测试它是否在$digest 中,然后仅在需要时调用$apply。这在构建绑定到发生在角度上下文之外的事件的指令时非常有用。

这是需要$timeout 时的指令场景:

app.directive('myDirective', function() {

    return {
        link: function(scope, element) {

            element.bind('click', function() {

                // $timeout is needed here because the 'click' event is outside angular
            }
        }
    }
});

【讨论】:

  • 我仍然不清楚为什么 setTimeout 在“myDirective”中不起作用。
  • 你有什么不清楚的地方? setTimeout 会起作用,但角度 $watch 队列仅由角度触发。如果您正在更改作用域属性,并且您不在 angular 范围内,则需要告诉 angular 再看一次。如果您还没有,请查看conceptual overviewAngular Is Slow
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 2015-03-27
  • 2010-10-27
  • 2015-01-18
  • 2010-12-24
  • 2013-03-18
  • 1970-01-01
相关资源
最近更新 更多