Skip to content

Instantly share code, notes, and snippets.

@mgebundy
Last active December 9, 2021 03:26
Show Gist options
  • Save mgebundy/44e3b5dd107d24cd07da to your computer and use it in GitHub Desktop.
Save mgebundy/44e3b5dd107d24cd07da to your computer and use it in GitHub Desktop.
AngularJS Countdown Directive
<time ng-countdown="1411225200" ng-countdown-finished="toggle()">
<ul class="timer_wrap">
<li class="days">
<span class="value" ng-bind="days">-</span>
<span class="label">days</span>
</li>
<li class="hours">
<span class="value" ng-bind="hours">--</span>
<span class="label">hours</span>
</li>
<li class="minutes">
<span class="value" ng-bind="minutes">--</span>
<span class="label">minutes</span>
</li>
<li class="seconds">
<span class="value" ng-bind="seconds">--</span>
<span class="label">seconds</span>
</li>
</ul>
</time>
app.directive('ngCountdown', function() {
return {
restrict: 'A',
controller: function($scope, $attrs, $timeout) {
var ds = new Date();
ds.setTime($attrs.ngCountdown * 1000);
$scope.days = '-';
$scope.hours = $scope.minutes = $scope.seconds = '--';
$scope.timeout = $timeout(update, 1000);
function update() {
now = +new Date();
$scope.delta = Math.round((ds - now) / 1000);
if ($scope.delta >= 0) {
$timeout(update, 1000);
} else if ($attrs.ngCountdownFinished) {
$scope.$apply($attrs.ngCountdownFinished);
}
}
},
link: function($scope, $element, $attrs) {
$scope.$watch('delta', function(delta) {
if (typeof delta === 'undefined') return;
if (delta < 0) {
delta = 0;
}
$scope.days = Math.floor(delta / 86400);
$scope.hours = forceTwoDigits(Math.floor(delta / 3600) % 24);
$scope.minutes = forceTwoDigits(Math.floor(delta / 60) % 60);
$scope.seconds = forceTwoDigits(delta % 60);
});
function forceTwoDigits(num) {
return String(num < 10 ? '0' + num : num);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment