【发布时间】:2016-09-12 17:42:41
【问题描述】:
我有一个计时器的 AngularJS 代码,在启动计数器时,计时器从 300 开始倒计时到 0。它工作正常。但是现在我想用 MM:SEC 格式(时钟)即 5:00 替换 300 并继续并在 0:00 结束,这是我无法做到的。我的代码
angular.module('TimerApp', [])
.controller('TimerCtrl', function($scope, $timeout) {
$scope.counter = 300;
var mytimeout = null; // the current timeoutID
// actual timer method, counts down every second, stops on zero
$scope.onTimeout = function() {
if ($scope.counter === 0) {
$scope.$broadcast('timer-stopped', 0);
$timeout.cancel(mytimeout);
return;
}
$scope.counter--;
mytimeout = $timeout($scope.onTimeout, 1000);
};
$scope.startTimer = function() {
mytimeout = $timeout($scope.onTimeout, 1000);
};
// stops and resets the current timer
$scope.stopTimer = function() {
$scope.$broadcast('timer-stopped', $scope.counter);
$scope.counter = 30;
$timeout.cancel(mytimeout);
};
// triggered, when the timer stops, you can do something here, maybe show a visual indicator or vibrate the device
$scope.$on('timer-stopped', function(event, remaining) {
if (remaining === 0) {
console.log('your time ran out!');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app='TimerApp'>
<div ng-controller="TimerCtrl">
{{counter}}
<button ng-click='startTimer()'>Start</button>
</div>
</div>
上面的工作 JSFiddle:http://jsfiddle.net/fq4vg/1796/
【问题讨论】:
标签: javascript angularjs