-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-countdown-timer.js
68 lines (59 loc) · 2.11 KB
/
angular-countdown-timer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function countdownTimerDirective() {
return {
restrict: 'EAC',
replace: false,
scope: {
countdown: "=",
interval: "=",
active: "=",
onZeroCallback: "="
},
template:"{{formatted}}",
controller: function ($scope, $attrs, $timeout) {
$scope.format = $attrs.outputFormat;
var queueTick = function () {
$scope.timer = $timeout(function () {
if ($scope.countdown > 0) {
$scope.countdown -= 1;
if ($scope.countdown > 0) {
queueTick();
} else {
$scope.countdown = 0;
$scope.active = false;
if (!_.isUndefined($scope.onZeroCallback)) {
$scope.onZeroCallback();
}
}
}
}, $scope.interval);
};
if ($scope.active) {
queueTick();
}
$scope.$watch('active', function (newValue, oldValue) {
if (newValue !== oldValue) {
if (newValue === true) {
if ($scope.countdown > 0) {
queueTick();
} else {
$scope.active = false;
}
} else {
$timeout.cancel($scope.timer);
}
}
});
$scope.$watch('countdown', function () {
updateFormatted();
});
var updateFormatted = function () {
$scope.formatted = moment($scope.countdown * $scope.interval).format($scope.format);
};
updateFormatted();
$scope.$on('$destroy', function () {
$timeout.cancel($scope.timer);
});
}
};
}
angular.module('angularCountdownTimer', []).directive('timer', countdownTimerDirective);