这是我的代码,但我无法在几分钟内找到倒计时,我的意思是,而不是3000,30:00 ......任何帮助?
<script>
app.controller("Counter", function($scope,$timeout){
$scope.counter = 3000;
$scope.onTimeout = function(){
$scope.counter--;
mytimeout = $timeout($scope.onTimeout,1000);
}
var mytimeout = $timeout($scope.onTimeout,1000);
});
</script>
答案 0 :(得分:8)
您的控制器没问题,您只需要:
counter
之前添加条件以避免转身:
if ($scope.counter > 0) $scope.counter--;
现在显示秒为'mm:ss'
将计数器转换为日期。您可以使用过滤器(来自此answer)
app.filter('secondsToDateTime', [function() {
return function(seconds) {
return new Date(1970, 0, 1).setSeconds(seconds);
};
}])
并显示如下:
{{counter | secondsToDateTime | date:'mm:ss'}}
在fiddle或下面的代码段中查看其工作原理。
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $timeout) {
$scope.counter = 1800;
$scope.onTimeout = function() {
if ($scope.counter > 0) $scope.counter--;
mytimeout = $timeout($scope.onTimeout, 1000);
}
var mytimeout = $timeout($scope.onTimeout, 1000);
}
myApp.filter('secondsToDateTime', [function() {
return function(seconds) {
return new Date(1970, 0, 1).setSeconds(seconds);
};
}])
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
{{counter | secondsToDateTime | date:'mm:ss'}}
</div>
&#13;
答案 1 :(得分:0)
这是一个简短的例子。
视图:
<div ng-controller="countCtrl">
<span>{{30 - secondsPassed/60}}:{{59 - secondsPassed%60}}</span>
<button ng-click="startTimer()">Click me to start the timer</button>
</div>
控制器:
.controller('countCtrl', function($scope, $interval){
$scope.secondsPassed = 0;
var ref;
$scope.startTimer = function(){
//Clean interval instance if button clicked multiple times.
$interval.cancel(ref);
$scope.secondsPassed = 0;
ref = $interval(function(){
$scope.secondsPassed++;
if($scope.secondsPassed >= 30 * 60){
//Clean interval instance if we passed the 30 min mark.
$interval.cancel(ref);
}
}, 1000);
};
//Clean the interval instance if scope destroyed
$scope.$on('$destroy', function(){
$interval.cancel(ref);
});
});
答案 2 :(得分:0)
上述答案会重置00:00秒后的时间,并再次从59:59开始倒计时。
我已经将答案更改为00:00后停止
app.controller('fiveCtrl', function ($scope, $timeout) {
$scope.counter = 3000;
$scope.onTimeout = function () {
if ($scope.counter == 0) {
$scope.counter = 0;
}
else{
$scope.counter--;
mytimeout = $timeout($scope.onTimeout, 1000);
}
}
var mytimeout = $timeout($scope.onTimeout, 1000);
});
app.filter('secondsToDateTime', [function() {
return function(seconds) {
return new Date(1970, 0, 1).setSeconds(seconds);
};
}])
Html将是
<div ng-controller="fiveCtrl">
<b> Test time Left : {{counter | secondsToDateTime | date:'mm:ss'}}</b>
<div ng-show="counter<60 && counter!=0"> Test expires in {{counter}} seconds</div>
<div ng-show="counter==0"> Test expired : {{counter}} seconds left</div>
</div>