angularjs make a simple countdown

来源:互联网 发布:建立数据标准化的意义 编辑:程序博客网 时间:2024/05/10 03:38


up vote35down votefavorite
12

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

Html File

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

js File

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!

shareimprove this question
 

8 Answers

activeoldestvotes
up vote45down vote

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/

JavaScript code:

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:

<!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>
shareimprove this answer
 
6 
Here is a modification that does a count down: jsfiddle.net/dpeaep/LQGE2/1 – Daniel Aug 21 '12 at 15:03
 
good, I used $interval instead of $timeout – Andres Oct 14 '14 at 18:23
 
How would you stop the clock? – Imray Jun 7 at 5:47
up vote15down vote

As of version 1.3 there's a service in module 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: http://docs.angularjs.org/api/ng/service/$interval

shareimprove this answer
 
 
Thanks. For anyone else wondering, this isn't limited to 1.3: code.angularjs.org/1.2.12/docs/api/ng.$interval – Hakan B. Mar 11 '14 at 21:04
up vote10down vote

Even easier, a pre-built directive:

http://siddii.github.io/angular-timer/

shareimprove this answer
 
up vote8down vote

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

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/

shareimprove this answer
 
14 
Directly using setTimeOut or setInterval is not a good practice in Angular. You should be using the $timeout service. – ganaraj Aug 21 '12 at 10:10
4 
@ganaraj It depends on the task. Practicality beats purity. – Artem Andreev Aug 21 '12 at 17:35
3 
There is the $timeout service in AngularJS that would call $apply automatically. – pkozlowski.opensourceAug 21 '12 at 21:04
1 
@pkozlowski.opensource Thanks, you didn't say anything new. I am able to read answers and comments :) I think that it is good to have two answers. One explains why code doesn't work and how you can make it work. And another that explains how it could be done in more angular way. – Artem Andreev Aug 22 '12 at 6:00
 
Your answer is much better. You are using interval which is much more suitable for a counter. – guy mograbi Apr 7 '13 at 6:12
up vote3down vote

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

it is here on 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

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));    };});
shareimprove this answer
 
 
Thanks for the useful format Filter – Rob Jan 7 at 18:28
up vote2down vote

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

Some great jsfiddle's by Igor Minar showing the use of $defer and wrapping $apply in a setInterval call.

shareimprove this answer
 
up vote0down vote
function timerCtrl ($scope,$interval) {    $scope.seconds = 0;    var timer = $interval(function(){        $scope.seconds++;        $scope.$apply();        console.log($scope.countDown);    }, 1000);}
shareimprove this answer
 
up vote0down vote

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

Step 1 : HTML Code-sample

<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

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.

<!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>
up vote35down votefavorite
12

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

Html File

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

js File

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!

shareimprove this question
 

8 Answers

activeoldestvotes
up vote45down vote

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/

JavaScript code:

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:

<!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>
shareimprove this answer
 
6 
Here is a modification that does a count down: jsfiddle.net/dpeaep/LQGE2/1 – Daniel Aug 21 '12 at 15:03
   
good, I used $interval instead of $timeout – Andres Oct 14 '14 at 18:23
   
How would you stop the clock? – Imray Jun 7 at 5:47
up vote15down vote

As of version 1.3 there's a service in module 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: http://docs.angularjs.org/api/ng/service/$interval

shareimprove this answer
 
   
Thanks. For anyone else wondering, this isn't limited to 1.3: code.angularjs.org/1.2.12/docs/api/ng.$interval – Hakan B. Mar 11 '14 at 21:04
up vote10down vote

Even easier, a pre-built directive:

http://siddii.github.io/angular-timer/

shareimprove this answer
 
up vote8down vote

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

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/

shareimprove this answer
 
14 
Directly using setTimeOut or setInterval is not a good practice in Angular. You should be using the $timeout service. – ganaraj Aug 21 '12 at 10:10
4 
@ganaraj It depends on the task. Practicality beats purity. – Artem Andreev Aug 21 '12 at 17:35
3 
There is the $timeout service in AngularJS that would call $apply automatically. – pkozlowski.opensourceAug 21 '12 at 21:04
1 
@pkozlowski.opensource Thanks, you didn't say anything new. I am able to read answers and comments :) I think that it is good to have two answers. One explains why code doesn't work and how you can make it work. And another that explains how it could be done in more angular way. – Artem Andreev Aug 22 '12 at 6:00
   
Your answer is much better. You are using interval which is much more suitable for a counter. – guy mograbi Apr 7 '13 at 6:12
up vote3down vote

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

it is here on 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

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));    };});
shareimprove this answer
 
   
Thanks for the useful format Filter – Rob Jan 7 at 18:28
up vote2down vote

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

Some great jsfiddle's by Igor Minar showing the use of $defer and wrapping $apply in a setInterval call.

shareimprove this answer
 
up vote0down vote
function timerCtrl ($scope,$interval) {    $scope.seconds = 0;    var timer = $interval(function(){        $scope.seconds++;        $scope.$apply();        console.log($scope.countDown);    }, 1000);}
shareimprove this answer
 
up vote0down vote

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

Step 1 : HTML Code-sample

<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

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.

<!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>
0 0
原创粉丝点击