javascript - 求大神:angularJS中倒计时60秒的按钮如何写?
黄舟
黄舟 2017-04-10 16:37:36
[JavaScript讨论组]

求大神:angularJS中倒计时60秒的按钮如何写?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(4)
高洛峰

我写的略多一点,plunker,是一个directive

index.html

<!DOCTYPE html>
<html ng-app="demo">

  <head>
    <script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body ng-controller="DemoCtrl">
    <h1>Hello Plunker!</h1>
    
    
    <timerbutton show-timer="true" timeout="time">Hello There</timerbutton>

  <script src="script.js"></script>
  </body>
</html>

script.js

// Code goes here

var demo = angular.module('demo', []);

demo.controller('DemoCtrl', function($scope){
  $scope.time = 6000;
});

demo.directive('timerbutton', function($timeout, $interval){
  return {
    restrict: 'AE',
    transclude: true,
    scope: {
      showTimer: '=',
      onClick: '&',
      timeout: '='
    },
    link: function(scope, element, attrs){
      scope.timer = true;
      scope.timerCount = scope.timeout;
      var counter = $interval(function(){
        scope.timerCount = scope.timerCount - 1000;
      }, 1000);
      
      $timeout(function(){
         scope.timer = false;
         $interval.cancel(counter);
         scope.showTimer = false;
      }, scope.timeout);
    },
    template: '<button ng-click="onClick()" ng-disabled="timer"><span ng-transclude></span>&nbsp<span ng-if="showTimer">({{ timerCount / 1000 }}s)</span></button>'
  };
});
PHPz

angular.module('myapp', [])
  .controller('demoController', ['$scope', '$interval', function($s, $i) {
    $s.time = 60;
    var timer = null;
    timer = $i(function(){
        $s.time = $s.time - 1;
        if($s.time === 0) {
            $i.cancel(timer);
        }
    }, 1000);
}]);
天蓬老师

写一个 directive(指令), 把1楼的倒计时封装上去, 如果要加回调用指令 isolate scope 的 & 传递函数名称。

高洛峰

$interval有循环多少次的功能
$interval(function (count){

//循环60次

} , 1000 , 60);

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号