【问题标题】:angularjs make a simple countdownangularjs做一个简单的倒计时
【发布时间】:2012-08-16 12:39:35
【问题描述】:

我想用 Angular js 倒计时。这是我的代码:

HTML 文件

<div ng-app ng-controller = "countController"> {{countDown}} <div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

js文件

function countController($scope){
    $scope.countDown = 10;    
    var timer = setInterval(function(){$scope.countDown--; console.log($scope.countDown)},1000);  
}​​

在 console.log 中它可以工作我有一个倒计时但在 {{countdown}} 刷新它没有 请问你能帮帮我吗?谢谢!

【问题讨论】:

标签: javascript html templates countdown angularjs


【解决方案1】:

请在此处查看此示例。这是一个计数的简单示例!我认为您可以轻松修改以创建倒计时。

http://jsfiddle.net/ganarajpr/LQGE2/

JavaScript 代码:

function AlbumCtrl($scope,$timeout) {
    $scope.counter = 0;
    $scope.onTimeout = function(){
        $scope.counter++;
        mytimeout = $timeout($scope.onTimeout,1000);
    }
    var mytimeout = $timeout($scope.onTimeout,1000);

    $scope.stop = function(){
        $timeout.cancel(mytimeout);
    }
}

HTML 标记:

<!doctype html>
<html ng-app>
<head>
    <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
    <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>
<body>
<div ng-controller="AlbumCtrl">
    {{counter}}
    <button ng-click="stop()">Stop</button>    
</div>
</body>
</html>

【讨论】:

【解决方案2】:

从 1.3 版开始,ng 模块中有一个服务:$interval

function countController($scope, $interval){
    $scope.countDown = 10;    
    $interval(function(){console.log($scope.countDown--)},1000,0);
}​​

谨慎使用:

注意:此服务创建的间隔必须显式销毁 当你完成与他们。特别是它们不是 当控制器的作用域或指令的作用域自动销毁 元素被破坏。您应该考虑到这一点并 确保始终在适当的时候取消间隔。看 下面的示例了解有关如何以及何时执行此操作的更多详细信息。

发件人:Angular's official documentation

【讨论】:

【解决方案3】:

当您从角度框架之外执行角度表达式时,您应该使用$scope.$apply()

function countController($scope){
    $scope.countDown = 10;    
    var timer = setInterval(function(){
        $scope.countDown--;
        $scope.$apply();
        console.log($scope.countDown);
    }, 1000);  
}

http://jsfiddle.net/andreev_artem/48Fm2/

【讨论】:

  • 直接使用 setTimeOut 或 setInterval 在 Angular 中不是一个好习惯。您应该使用 $timeout 服务。
  • @ganaraj 这取决于任务。实用胜于纯洁。
  • AngularJS 中有 $timeout 服务会自动调用 $apply。
  • @pkozlowski.opensource 谢谢,你没有说什么新东西。我能够阅读答案和 cmets :) 我认为有两个答案很好。其中一个解释了为什么代码不起作用以及如何使它起作用。另一个解释了如何以更有角度的方式完成。
  • 您的回答要好得多。您正在使用更适合计数器的间隔。
【解决方案4】:

我更新了 ganaraj 先生的答案以显示停止和恢复功能,并添加了 angular js 过滤器来格式化倒数计时器

it is here on jsFiddle

控制器代码

'use strict';
var myApp = angular.module('myApp', []);
myApp.controller('AlbumCtrl', function($scope,$timeout) {
    $scope.counter = 0;
    $scope.stopped = false;
    $scope.buttonText='Stop';
    $scope.onTimeout = function(){
        $scope.counter++;
        mytimeout = $timeout($scope.onTimeout,1000);
    }
    var mytimeout = $timeout($scope.onTimeout,1000);
    $scope.takeAction = function(){
        if(!$scope.stopped){
            $timeout.cancel(mytimeout);
            $scope.buttonText='Resume';
        }
        else
        {
            mytimeout = $timeout($scope.onTimeout,1000);
            $scope.buttonText='Stop';
        }
            $scope.stopped=!$scope.stopped;
    }   
});

过滤器代码改编自stackoverflow的RobG

myApp.filter('formatTimer', function() {
  return function(input)
    {
        function z(n) {return (n<10? '0' : '') + n;}
        var seconds = input % 60;
        var minutes = Math.floor(input / 60);
        var hours = Math.floor(minutes / 60);
        return (z(hours) +':'+z(minutes)+':'+z(seconds));
    };
});

【讨论】:

  • 我不认为格式计时器返回正确答案。假设输入是 7200。它将返回 02:120:00。我认为你应该先计算小时来格式化计时器。
【解决方案5】:

这可能有助于“如何在 AngularJS 中编写倒计时手表的代码”

第 1 步:HTML 代码示例

<div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>

第 2 步:AngulaJs 代码示例

function ExampleCtrl($scope, $timeout) {
  var countDowner, countDown = 10;
  countDowner = function() {
    if (countDown < 0) {
      $("#warning").fadeOut(2000);
      countDown = 0;
      return; // quit
    } else {
      $scope.countDown_text = countDown; // update scope
      countDown--; // -1
      $timeout(countDowner, 1000); // loop it again
    }
  };

  $scope.countDown_text = countDown;
  countDowner()
}

AngularJs 中倒计时手表的完整示例如下所示。

<!DOCTYPE html>
<html>

<head>
  <title>AngularJS Example - Single Timer Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  <script>
    function ExampleCtrl($scope, $timeout) {
      var countDowner, countDown = 10;
      countDowner = function() {
        if (countDown < 0) {
          $("#warning").fadeOut(2000);
          countDown = 0;
          return; // quit
        } else {
          $scope.countDown_text = countDown; // update scope
          countDown--; // -1
          $timeout(countDowner, 1000); // loop it again
        }
      };

      $scope.countDown_text = countDown;
      countDowner()
    }
  </script>
</head>

<body>
  <div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
  </div>
</body>

</html>

【讨论】:

    【解决方案6】:

    您可能没有正确声明您的模块,或者您在声明模块之前放置了函数(安全规则是在加载所有页面后将 angular 模块放在主体之后)。由于您使用的是 angularjs,那么您应该使用 $interval(angularjs 等效于 setInterval,它是一个 Windows 服务)。

    这是一个可行的解决方案:

    angular.module('count', [])
      .controller('countController', function($scope, $interval) {
        $scope.countDown = 10;
        $interval(function() {
          console.log($scope.countDown--);
        }, 1000, $scope.countDown);
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.1/angular.min.js"></script>
    
    
    <body>
      <div ng-app="count" ng-controller="countController"> {{countDown}} </div>
    </body>

    注意:它在 html 视图中停在 0 处,但在 console.log 中停在 1 处,你能找出原因吗? ;)

    【讨论】:

    • 如果您在docs.angularjs.org/api/ng/service/$interval 查找 $interval 使用情况,代码非常简单。 $interval 启动一个每秒钟减少 countDown 的服务(即 1000 = 1 秒),第三个参数告诉它执行 10 倍(因为 $scope.countDown 初始值为 10)。
    【解决方案7】:

    按照我的方式,它有效!

    • *angular 版本 1.5.8 及更高版本。

    角度代码

    var app = angular.module('counter', []);
    
    app.controller('MainCtrl', function($scope, $interval) {
      var decrementCountdown = function() {
        $scope.countdown -= 1;
        if ($scope.countdown < 1) {
          $scope.message = "timed out";
        }
      };
      var startCountDown = function() {
        $interval(decrementCountdown, 1000, $scope.countdown)
      };
      $scope.countdown = 100;
      startCountDown();
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
    
    
    
    <body ng-app="counter" ng-controller="MainCtrl">
      {{countdown}} {{message}}
    </body>

    【讨论】:

      【解决方案8】:
      function timerCtrl ($scope,$interval) {
          $scope.seconds = 0;
          var timer = $interval(function(){
              $scope.seconds++;
              $scope.$apply();
              console.log($scope.countDown);
          }, 1000);
      }
      

      【讨论】:

        【解决方案9】:
        var timer_seconds_counter = 120;
        $scope.countDown = function() {
              timer_seconds_counter--;
              timer_object = $timeout($scope.countDown, 1000);
              $scope.timer = parseInt(timer_seconds_counter / 60) ? parseInt(timer_seconds_counter / 60) : '00';
              if ((timer_seconds_counter % 60) < 10) {
                $scope.timer += ':' + ((timer_seconds_counter % 60) ? '0' + (timer_seconds_counter % 60) : '00');
              } else {
                $scope.timer += ':' + ((timer_seconds_counter % 60) ? (timer_seconds_counter % 60) : '00');
              }
              $scope.timer += ' minutes'
              if (timer_seconds_counter === 0) {
                timer_seconds_counter = 30;
                $timeout.cancel(timer_object);
                $scope.timer = '2:00 minutes';
              }
            }
        

        【讨论】:

          【解决方案10】:
          $scope.countDown = 30;
          var timer;
          $scope.countTimer = function () {
              var time = $timeout(function () {
                   timer = setInterval(function () {
                       if ($scope.countDown > 0) {
                           $scope.countDown--;
                      } else {
                          clearInterval(timer);
                          $window.location.href = '/Logoff';
                      }
                      $scope.$apply();
                  }, 1000);
              }, 0);
          }
          
          $scope.stop= function () {
              clearInterval(timer);
              
          }
          

          在 HTML 中:

          <button type="submit" ng-click="countTimer()">Start</button>
          <button type="submit" ng-click="stop()">Clear</button>
                           
                          
                        
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-09
            • 1970-01-01
            • 2016-08-04
            • 1970-01-01
            • 2010-11-14
            • 2012-09-07
            相关资源
            最近更新 更多