angularjs使用directive實現倒計時按鈕


前不久在做一個彩票的項目時,有一個手動開獎的需求。所以有了這個倒計時按鈕。下面分享下具體的代碼:

效果:

 

代碼:

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>

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM