前不久在做一個彩票的項目時,有一個手動開獎的需求。所以有了這個倒計時按鈕。下面分享下具體的代碼:
效果:
代碼:
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>