为什么我的AngularJS取消间隔工作

时间:2015-10-30 03:26:40

标签: javascript angularjs timer countdown

我想在按下停止计时器时停止倒计时。我不知道为什么这不起作用。我有一个简单的jsfiddle设置here

CODE
视图

<div ng-app="timerApp" ng-controller="timerController">
    <h4>Time Remaining: {{countdown}}</h4>
    <button ng-click="startTimer()">Start Timer</button>
    <button ng-click="stopTimer()">Stop Timer</button>
</div>

控制器

angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval', function ($scope, $interval) {
    var timer;
    var time = 10;
    $scope.countdown = time;

    $scope.stopTimer = function() {
        $interval.cancel(timer);
    };

    $scope.startTimer = function() {
        timer = $interval(function() {
           $scope.countdown--;
        }, 1000, time).then(function() {
            $scope.countdown = time;
        });
    };

}]);

1 个答案:

答案 0 :(得分:14)

问题是调用then返回一个新承诺,而不是$interval方法所需的$interval.cancel()返回的承诺

&#13;
&#13;
angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval',
  function($scope, $interval) {
    var timer;
    var time = 10;
    $scope.countdown = time;

    $scope.stopTimer = function() {
      $interval.cancel(timer);
    };

    $scope.startTimer = function() {
      timer = $interval(function() {
        $scope.countdown--;
      }, 1000, time);
      timer.then(function() {
        $scope.countdown = time;
      });
    };

  }
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="timerApp" ng-controller="timerController">
  <h4>Time Remaining: {{countdown}}</h4>
  <button ng-click="startTimer()">Start Timer</button>
  <button ng-click="stopTimer()">Stop Timer</button>
</div>
&#13;
&#13;
&#13;