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

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

阅读 8.4k
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>'
  };
});

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);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题