Last active
December 9, 2021 03:26
-
-
Save mgebundy/44e3b5dd107d24cd07da to your computer and use it in GitHub Desktop.
AngularJS Countdown Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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