Javascript angularjs 做一个简单的倒计时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12050268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:59:52  来源:igfitidea点击:

angularjs make a simple countdown

javascripthtmltemplatescountdownangularjs

提问by ganaraj

I would like make a countDown with Angular js. this is my code:

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

Html File

html文件

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

js File

js文件

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

in console.log it works I have a countdown but in {{countdown}} refresh it doesn't could you help me please? thanks!

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

回答by ganaraj

Please take a look at this example here. It is a simple example of a count up! Which I think you could easily modify to create a count down.

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

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

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

JavaScript code:

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 markup:

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>

回答by jpfreire

As of version 1.3 there's a service in module ng: $interval

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

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

Use with caution:

谨慎使用:

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

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

From: Angular's official documentation.

来自:Angular 的官方文档

回答by Artem Andreev

You should use $scope.$apply()when you execute an angular expression from outside of the angular framework.

当您从 angular 框架之外执行 angular 表达式时,您应该使用$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/

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

回答by Shaheen

I updated Mr. ganaraj answer to show stop and resume functionality and added angular js filter to format countdown timer

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

it is here on jsFiddle

它在 jsFiddle 上

controller code

控制器代码

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

filter-code adapted from RobG from stackoverflow

过滤器代码改编自来自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));
    };
});

回答by Anil Singh

It might help to "How to write the code for countdown watch in AngularJS"

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

Step 1 : HTML Code-sample

第 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>

Step 2 : The AngulaJs code-sample

第 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()
}

The full example over countdown watch in AngularJs as given below.

下面给出了 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>

回答by Tan Tran

You probably didn't declare your module correctly, or you put the function before the module is declared (safe rule is to put angular module after the body, once all the page is loaded). Since you're using angularjs, then you should use $interval(angularjs equivalence to setInterval which is a windows service).

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

Here is a working solution:

这是一个有效的解决方案:

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>

Note: it stops at 0 in the html view, but at 1 in the console.log, can you figure out why? ;)

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

回答by kingsman

The way I did , it works!

按照我的方法,有效!

  • *angular version 1.5.8 and above.
  • *angular 1.5.8 及以上版本。

Angular code

角码

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

app.controller('MainCtrl', function($scope, $interval) {
  var decreamentCountdown = function() {
    $scope.countdown -= 1;
    if ($scope.countdown < 1) {
      $scope.message = "timed out";
    }
  };
  var startCountDown = function() {
    $interval(decreamentCountdown, 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>

回答by Partha Roy

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';
      }
    }

回答by Betite

function timerCtrl ($scope,$interval) {
    $scope.seconds = 0;
    var timer = $interval(function(){
        $scope.seconds++;
        $scope.$apply();
        console.log($scope.countDown);
    }, 1000);
}