Im in need to make a countdown like this:
<div class="countdown" countdown="1482400417">00:10:02</div>
where the countdown attribute is the time when its finished. the difference is showed in hours:minutes:secs , and it updates each second.
How would i do this in angularjs, when i have multiple countdowns like that?
I did a little digging, and i found something that did something simular, but i couldnt understand the code. So ill post the code i found:
Travian.Directive.countdown = function(a) {
return function(c, b, l) {
function g() {
if ("undefined" != typeof a.K()) {
h = b.attr("countdown");
var c = h - a.K();
if (0 > c || isNaN(c)) {
return Travian.tick.unbind(e), e = null, b.text(
la(0)), !1
}
var g = "";
l.showDaysLimit && c >= l.showDaysLimit ? (c = Math
.round(c / 86400), c == f ? g = m : (g =
Travian.translate("ForDays", {
x: c
}), f = c)) : g = la(c, l.countdownShort &&
c < l.countdownShort);
m != g && (m = g, b.text(g))
}
}
var h, e = null,
m = "",
f = 0;
l.showDaysLimit && c.$on("newTranslation", function() {
f = 0
});
l.$observe("countdown", function(a) {
"undefined" != typeof a && null == e && (e =
Travian.tick.bind(g))
});
b.bind("$destroy", function() {
Travian.tick.unbind(e)
})
}
};
Travian.tick = new function() {
var a = {};
(function B() {
window.setTimeout(B, 100);
var b = {}, c;
for(c in a) {
a.hasOwnProperty(c) && "function" === typeof a[c] && (a[c](), b[c] = a[c])
}
a = b
})();
return{bind:function(b, c) {
"function" === typeof b && (c = b, b = na("tick"));
c();
a[b] = c;
return b
}, unbind:function(b) {
a[b] = null
}}
};
Not exactly what you asked for, but that should get you started.
You can create a directive that has and displays a countdown value. This value is updated every second using $interval
service.
myApp.directive('countdown', function() {
return {
restrict: 'E',
template: '<div>{{countdownVal}}</div>',
scope: {
initVal: '='
},
controller: function($scope, $interval) {
$scope.countdownVal = $scope.initVal;
$interval(function () {
if ($scope.countdownVal > 0) {}
$scope.countdownVal--;
}
}, 1000);
}
}
});
Having this has a starting point, you can tweak this code to add formatting, and to make this directive usable as an attribute instead of as a element.
See a concrete example in this JSFiddle.
Also, keep in mind that you should destroy the interval when you are done with it. From the docs:
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.