2015-10-30 41 views
4

我想按停止計時器時停止倒計時。我不知道爲什麼這不起作用。我有一個簡單的jsfiddle設置here爲什麼我的AngularJS取消間隔工作不正常

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; 
     }); 
    }; 

}]); 

回答

11

的問題是通話then返回不是由$interval返回一個它是由$interval.cancel()方法需要新的承諾

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; 
 
     }); 
 
    }; 
 

 
    } 
 
]);
<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>

+0

你值得+100對這個我已經失去了我的早晨在這個怪異的行爲... – Mouss