Angular Countdown Timer Directive
by Premchand R
HTML
<div class='wrap' ng-app='app'>
<div class='time-to'>
<countdown date='December 1, 2017 9:00:00'></countdown>
</div>
</div>
CSS
@import "//fonts.googleapis.com/css?family=Bangers";
body {
margin: 0;
}
.wrap {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
height: 100vh;
background: black;
}
.time-to {
text-align: center;
font-family: Bangers;
color: white;
font-size: 35px;
letter-spacing: 2px;
}
.time-to span {
display: block;
font-size: 80px;
color: red;
}
JavaScript
(function () {
angular.module('app', []).directive('countdown', [
'Util',
'$interval',
function (Util, $interval) {
return {
restrict: 'E',
scope: { date: '@' },
template:'<div style="background-color:red;"></div>',
replace:true,
link: function (scope, element) {
var future;
future = new Date(scope.date);
$interval(function () {
var diff;
diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
return element.text(Util.dhms(diff));
}, 1000);
}
};
}
]).factory('Util', [function () {
return {
dhms: function (t) {
var days, hours, minutes, seconds;
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;
return [
days + 'd',
hours + 'h',
minutes + 'm',
seconds + 's'
].join(' ');
}
};
}]);
}.call(this));