angularjs做一个简单的倒计时

时间:2012-08-21 07:39:03

标签: javascript html templates countdown angularjs

我想用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中它是有效的,我有一个倒计时,但在{{countdown}}刷新它没有 请问你能帮帮我吗?谢谢!

11 个答案:

答案 0 :(得分:58)

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

<强> 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 :(得分:24)

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

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

谨慎使用:

  

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

来自:Angular's official documentation

答案 2 :(得分:9)

从角度框架外部执行角度表达式时,应使用$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/

答案 3 :(得分:7)

我更新了ganaraj先生的回答显示停止和恢复功能,并添加了角度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));
    };
});

答案 4 :(得分:2)

https://groups.google.com/forum/?fromgroups=#!topic/angular/2MOB5U6Io0A

Igor Minar的一些伟大的jsfiddle显示在setInterval调用中使用$ defer和wrap $ apply。

答案 5 :(得分:1)

对于“如何在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 :(得分:1)

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

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

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>AngularJS countDown</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
    </head>
    <body>
        <div ng-app="count" ng-controller = "countController"> {{countDown}} </div>
    </body>
    <script>
        angular.module('count', [])
        .controller('countController',function($scope, $interval){
            $scope.countDown=10;
            $interval(function(){
                console.log($scope.countDown--);
            },1000, $scope.countDown);
        });
    </script>
</html>

注意:它在html视图中停在0,但在console.log中为1,你能弄明白为什么吗? ;)

答案 7 :(得分:0)

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

答案 8 :(得分:0)

我的方式,它有效!

  • *角度版本1.5.8及以上。

角度代码

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

Html查看代码。

<!DOCTYPE html>
<html ng-app="counter">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link href="style.css" rel="stylesheet" />
<script src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8" data-require="angular.js@1.5.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
{{countdown}}
{{message}}
</body>
</html>

答案 9 :(得分:0)

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 :(得分:0)

// Share doc
func shareDocAction() {

    let path = Bundle.main.path(forResource: nameFile,  ofType: "pdf")
    let fileURL = URL(fileURLWithPath: path!)

    // Make the activityViewContoller which shows the share-view
    let activityViewController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)

    // Show the share-view
    self.present(activityViewController, animated: true)
}

在HTML中:

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