angularjs make a simple countdown angularjs make a simple countdown angularjs angularjs

angularjs make a simple countdown


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>


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: Angular's official documentation.


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/