前不久在做一个彩票的项目时,有一个手动开奖的需求。所以有了这个倒计时按钮。下面分享下具体的代码:
效果:
代码:
App.directive('timerBtn', function() { // 倒计时按钮
return {
restrict: 'A',
replace: true,
scope: {
startTime: '=startTime',
getData: '&getData'
},
template: '<button class="btn btn-danger" style="border-radius: 30px;padding: 3px 16px;" ng-disabled="startTime> 0" ng-bind="startTime > 0 ? showTime + \' 后开奖\' : \'手动开奖\'" ng-click="getData()"></button>',
controller: function($scope, $interval) { var formatTime = function(second) {
return [parseInt(second / 60 / 60), parseInt(second / 60 % 60), second % 60].join(":")
.replace(/\b(\d)\b/g, "0$1");
} var timer = $interval(function() {
$scope.startTime -= 1;
$scope.showTime = formatTime($scope.startTime);
if($scope.startTime < 1) {
$interval.cancel(timer);
};
}, 1000); }
};
});
这个组件接受两个参数:
startTime:用于接收倒计时开始时间的时间戳
getData:用于接收倒计时结束之后触发的函数 用法:
<div timer-btn start-time="time" get-data="getData()"></div>