【问题标题】:Update variable in every tick using setInterval() with AngularJS使用带有 AngularJS 的 setInterval() 在每个刻度中更新变量
【发布时间】:2015-06-29 17:17:47
【问题描述】:

我正在尝试使用 setInterval() 在 JS 中每隔 x 秒计算一个变量,并在我的视图中显示它以 Angular 方式绑定该变量。问题是,在模型中,var 被计数,但只要我停止 Interval,就会显示进度。如何在每次滴答时更新视图中的 var?

<span>{{number}}</span> 

和:

$scope.number = 0;
$scope.interval;

$scope.run = function(){
    $scope.interval = setInterval(function(){
        $scope.number++;
    }, 1000);
};

$scope.stop = function(){
    clearInterval($scope.interval);
}

Fiddle

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您应该使用 Angular 的 setInterval 实现,称为 $interval。

    这不仅可以确保回调中的任何代码都调用摘要,还可以帮助您轻松测试代码:

    $scope.run = function() {
        $scope.interval = $interval(function() {
            $scope.number++;
        }, 1000);
    };
    $scope.stop = function() {
        $interval.cancel($scope.interval);
    };
    

    我也会避免将您的interval 变量附加到$scope。我看不出您的观点需要意识到它的任何理由。控制器范围内的私有var interval 就足够了。

    【讨论】:

      【解决方案2】:
      var myApp = angular.module('myApp', []);
      
      myApp.controller('MyCtrl', function ($scope, $interval) {
          $scope.number = 0;
      
          $scope.run = function (){
              $scope.interval = $interval(function(){ 
                  $scope.number++;
              }, 1000);
          };
      
          $scope.stop = function() {
              $interval.cancel($scope.interval);
          };
      

      });

      【讨论】:

        猜你喜欢
        • 2021-09-24
        • 2020-07-04
        • 2020-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-29
        • 1970-01-01
        • 2019-03-12
        相关资源
        最近更新 更多