Dan*_*obe 4 javascript timer countdown angularjs
我想在按下停止计时器时停止倒计时.我不知道为什么这不起作用.我在这里设置了一个简单的jsfiddle .
代码
视图
<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>
Run Code Online (Sandbox Code Playgroud)
调节器
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;
});
};
}]);
Run Code Online (Sandbox Code Playgroud)
Aru*_*hny 14
问题是call then返回一个新的promise,而不是方法$interval所需返回的promise$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;
});
};
}
]);Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2774 次 |
| 最近记录: |