前端学习——ionic/AngularJs——获取验证码倒计时按钮

本文介绍了一种使用Angular实现的验证码倒计时按钮功能,通过设置$interval和$timeout来控制按钮的状态,包括禁用、显示倒计时及60秒后重新启用。文章提供了完整的directive代码和HTML示例,展示了按钮从正常状态到倒计时状态的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

按钮功能为:点击“获取验证码”——按钮不可用-设置倒计时-60秒后重新获取。

代码借鉴于:http://plnkr.co/edit/Swj82MpJSix3a47jZRHP?p=preview

主要实现原理:点击后,设置一个$interval,每一秒更改一次剩余时间,并依赖Angular数据绑定实时显示在页面中。设置一个$timeout,60秒后将按钮初始化到可用状态。

实现代码:

(1)js代码,设置成一个directive以便多次调用。

angular.module('winwin').directive('timerbutton', function($timeout, $interval){
    return {
        restrict: 'AE',
        scope: {
            showTimer: '=',
            timeout: '='
        },
        link: function(scope, element, attrs){
            scope.timer = false;
            scope.timeout = 60000;
            scope.timerCount = scope.timeout / 1000;
            scope.text = "获取验证码";

            scope.onClick = function(){
                scope.showTimer = true;
                scope.timer = true;
                scope.text = "秒后重新获取";
                var counter = $interval(function(){
                    scope.timerCount = scope.timerCount - 1;
                }, 1000);

                $timeout(function(){
                    scope.text = "获取验证码";
                    scope.timer = false;
                    $interval.cancel(counter);
                    scope.showTimer = false;
                    scope.timerCount = scope.timeout / 1000;
                }, scope.timeout);
            }
        },
        template: '<button on-tap="onClick()" class="button button-calm xgmm-btn" ng-disabled="timer"><span ng-if="showTimer">{{ timerCount }}</span>{{text}}</button>'
    };
});

(2)html代码

 <timerbutton show-timer="false">获取验证码</timerbutton>

实现效果:

(1)点击之前

  

(2)点击之后

  

 

转载于:https://www.cnblogs.com/Damono/p/5649789.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值