angularjs做一个简单的倒计时

angularjs make a simple countdown

本文关键字:一个 简单 倒计时 angularjs      更新时间:2023-09-26

我想用Angular js做一个countDown。这是我的代码:

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中它有效我有倒计时,但在{{倒计时}}刷新中它没有你能帮我吗?谢谢

请看一下这个例子。这是一个简单的计数示例!我认为你可以很容易地修改它来创建倒计时。

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>

自版本1.3起,模块ng:$interval 中有一项服务

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

小心使用:

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

来源: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/

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

它在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));
    };
});

这可能有助于"如何在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>

您可能没有正确声明模块,或者您将函数放在声明模块之前(安全规则是,一旦加载了所有页面,就将角度模块放在主体之后)。既然您使用的是angularjs,那么您应该使用$interval(angular js相当于windows服务的setInterval)。

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

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,你能找出原因吗?;)

按照我的方式,它是有效的!

  • *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>

function timerCtrl ($scope,$interval) {
    $scope.seconds = 0;
    var timer = $interval(function(){
        $scope.seconds++;
        $scope.$apply();
        console.log($scope.countDown);
    }, 1000);
}
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';
      }
    }
$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>