我想在按下停止计时器时停止倒计时。我不知道为什么这不起作用。我有一个简单的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;
});
};
}]);
答案 0 :(得分:14)
问题是调用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;
});
};
}
]);
&#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;