app中发送短信验证码,一般都有60s的倒计时,这个其实利用好angularjs,封装成指令,可重复利用
1. drCountdown
/**
* Created by dzm on 2016/1/18.
* 倒计时指令按钮
* initText:初始显示的文本
* changeText:改变之后的文本
* btnClick:指令调用的点击事件,通常是controller中的方法
* countDown:倒计时
* btnDisabled:按钮可用性设置
* 参考示例如下:
* <dr-countdown init-text="获取验证码" change-text="重新发送" count-down="60" btn-disabled="forgetPwdForm.mobile.$invalid" btn-click="sendSms()"></dr-countdown>
*/
directives.directive('drCountdown', function ($interval) {
return {
restrict:'AE',
scope:{changeText:'@',initText:'@',btnClick:'&',countDown:'@',btnDisabled:'='},
template:'<a class="button button-balanced" ng-disabled="btnDisabled" ng-click="down()" >{{btnText}}</a>',
link:function(scope,element, attrs,ctrl){
scope.btnText = scope.initText;
// scope.btnDisabled = true;
scope.down = function () {
var iTimes = scope.countDown;
scope.btnText = '('+iTimes+')秒'+scope.changeText;
scope.btnDisabled = true;
scope.btnClick();
//
var timer = $interval(function(){
iTimes--;
scope.btnText = '('+iTimes+')秒'+scope.changeText;
if (iTimes==0){
$interval.cancel(timer);
scope.btnText = scope.initText;
scope.btnDisabled =false;
}
},1000);
}
}
}
});
2. controller
controller主要写指令中btnClick方法的业务逻辑,示例如下:
/**
* 发送短信
*/
$scope.sendSms = function(){
AcsService.sms01($scope.user.mobile).then(function(resp){
if (resp.success){
IonicNoticeService.show("短信验证码已发送至"+$scope.user.mobile);
}
});
}
3 效果