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