2 * angular-timer - v1.3.3 - 2015-05-28 9:05 AM
3 * https://github.com/siddii/angular-timer
5 * Copyright (c) 2015 Siddique Hameed
6 * Licensed MIT <https://github.com/siddii/angular-timer/blob/master/LICENSE.txt>
8 var timerModule = angular.module('timer', [])
9 .directive('timer', ['$compile', function ($compile) {
14 interval: '=interval',
15 startTimeAttr: '=startTime',
16 endTimeAttr: '=endTime',
17 countdownattr: '=countdown',
18 finishCallback: '&finishCallback',
19 autoStart: '&autoStart',
24 controller: ['$scope', '$element', '$attrs', '$timeout', 'I18nService', '$interpolate', 'progressBarService', function ($scope, $element, $attrs, $timeout, I18nService, $interpolate, progressBarService) {
26 // Checking for trim function since IE8 doesn't have it
27 // If not a function, create tirm with RegEx to mimic native trim
28 if (typeof String.prototype.trim !== 'function') {
29 String.prototype.trim = function () {
30 return this.replace(/^\s+|\s+$/g, '');
34 //angular 1.2 doesn't support attributes ending in "-start", so we're
35 //supporting both "autostart" and "auto-start" as a solution for
36 //backward and forward compatibility.
37 $scope.autoStart = $attrs.autoStart || $attrs.autostart;
40 $scope.language = $scope.language || 'en';
41 $scope.fallback = $scope.fallback || 'en';
43 //allow to change the language of the directive while already launched
44 $scope.$watch('language', function(newVal, oldVal) {
45 if(newVal !== undefined) {
46 i18nService.init(newVal, $scope.fallback);
50 //init momentJS i18n, default english
51 var i18nService = new I18nService();
52 i18nService.init($scope.language, $scope.fallback);
55 $scope.displayProgressBar = 0;
56 $scope.displayProgressActive = 'active'; //Bootstrap active effect for progress bar
58 if ($element.html().trim().length === 0) {
59 $element.append($compile('<span>' + $interpolate.startSymbol() + 'millis' + $interpolate.endSymbol() + '</span>')($scope));
61 $element.append($compile($element.contents())($scope));
64 $scope.startTime = null;
65 $scope.endTime = null;
66 $scope.timeoutId = null;
67 $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) >= 0 ? parseInt($scope.countdownattr, 10) : undefined;
68 $scope.isRunning = false;
70 $scope.$on('timer-start', function () {
74 $scope.$on('timer-resume', function () {
78 $scope.$on('timer-stop', function () {
82 $scope.$on('timer-clear', function () {
86 $scope.$on('timer-reset', function () {
90 $scope.$on('timer-set-countdown', function (e, countdown) {
91 $scope.countdown = countdown;
94 function resetTimeout() {
95 if ($scope.timeoutId) {
96 clearTimeout($scope.timeoutId);
100 $scope.$watch('startTimeAttr', function(newValue, oldValue) {
101 if (newValue !== oldValue && $scope.isRunning) {
106 $scope.$watch('endTimeAttr', function(newValue, oldValue) {
107 if (newValue !== oldValue && $scope.isRunning) {
112 $scope.start = $element[0].start = function () {
113 $scope.startTime = $scope.startTimeAttr ? moment($scope.startTimeAttr) : moment();
114 $scope.endTime = $scope.endTimeAttr ? moment($scope.endTimeAttr) : null;
115 if (!$scope.countdown) {
116 $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
120 $scope.isRunning = true;
123 $scope.resume = $element[0].resume = function () {
125 if ($scope.countdownattr) {
126 $scope.countdown += 1;
128 $scope.startTime = moment().diff((moment($scope.stoppedTime).diff(moment($scope.startTime))));
130 $scope.isRunning = true;
133 $scope.stop = $scope.pause = $element[0].stop = $element[0].pause = function () {
134 var timeoutId = $scope.timeoutId;
136 $scope.$emit('timer-stopped', {timeoutId: timeoutId, millis: $scope.millis, seconds: $scope.seconds, minutes: $scope.minutes, hours: $scope.hours, days: $scope.days});
139 $scope.clear = $element[0].clear = function () {
140 // same as stop but without the event being triggered
141 $scope.stoppedTime = moment();
143 $scope.timeoutId = null;
144 $scope.isRunning = false;
147 $scope.reset = $element[0].reset = function () {
148 $scope.startTime = $scope.startTimeAttr ? moment($scope.startTimeAttr) : moment();
149 $scope.endTime = $scope.endTimeAttr ? moment($scope.endTimeAttr) : null;
150 $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
153 $scope.isRunning = false;
157 $element.bind('$destroy', function () {
159 $scope.isRunning = false;
163 function calculateTimeUnits() {
164 var timeUnits = {}; //will contains time with units
166 if ($attrs.startTime !== undefined){
167 $scope.millis = moment().diff(moment($scope.startTimeAttr));
170 timeUnits = i18nService.getTimeUnits($scope.millis);
172 // compute time values based on maxTimeUnit specification
173 if (!$scope.maxTimeUnit || $scope.maxTimeUnit === 'day') {
174 $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
175 $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
176 $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
177 $scope.days = Math.floor((($scope.millis / (3600000)) / 24));
180 } else if ($scope.maxTimeUnit === 'second') {
181 $scope.seconds = Math.floor($scope.millis / 1000);
187 } else if ($scope.maxTimeUnit === 'minute') {
188 $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
189 $scope.minutes = Math.floor($scope.millis / 60000);
194 } else if ($scope.maxTimeUnit === 'hour') {
195 $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
196 $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
197 $scope.hours = Math.floor($scope.millis / 3600000);
201 } else if ($scope.maxTimeUnit === 'month') {
202 $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
203 $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
204 $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
205 $scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
206 $scope.months = Math.floor((($scope.millis / (3600000)) / 24) / 30);
208 } else if ($scope.maxTimeUnit === 'year') {
209 $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
210 $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
211 $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
212 $scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
213 $scope.months = Math.floor((($scope.millis / (3600000)) / 24 / 30) % 12);
214 $scope.years = Math.floor(($scope.millis / (3600000)) / 24 / 365);
216 // plural - singular unit decision (old syntax, for backwards compatibility and English only, could be deprecated!)
217 $scope.secondsS = ($scope.seconds === 1) ? '' : 's';
218 $scope.minutesS = ($scope.minutes === 1) ? '' : 's';
219 $scope.hoursS = ($scope.hours === 1) ? '' : 's';
220 $scope.daysS = ($scope.days === 1)? '' : 's';
221 $scope.monthsS = ($scope.months === 1)? '' : 's';
222 $scope.yearsS = ($scope.years === 1)? '' : 's';
225 // new plural-singular unit decision functions (for custom units and multilingual support)
226 $scope.secondUnit = timeUnits.seconds;
227 $scope.minuteUnit = timeUnits.minutes;
228 $scope.hourUnit = timeUnits.hours;
229 $scope.dayUnit = timeUnits.days;
230 $scope.monthUnit = timeUnits.months;
231 $scope.yearUnit = timeUnits.years;
233 //add leading zero if number is smaller than 10
234 $scope.sseconds = $scope.seconds < 10 ? '0' + $scope.seconds : $scope.seconds;
235 $scope.mminutes = $scope.minutes < 10 ? '0' + $scope.minutes : $scope.minutes;
236 $scope.hhours = $scope.hours < 10 ? '0' + $scope.hours : $scope.hours;
237 $scope.ddays = $scope.days < 10 ? '0' + $scope.days : $scope.days;
238 $scope.mmonths = $scope.months < 10 ? '0' + $scope.months : $scope.months;
239 $scope.yyears = $scope.years < 10 ? '0' + $scope.years : $scope.years;
243 //determine initial values of time units and add AddSeconds functionality
244 if ($scope.countdownattr) {
245 $scope.millis = $scope.countdownattr * 1000;
247 $scope.addCDSeconds = $element[0].addCDSeconds = function (extraSeconds) {
248 $scope.countdown += extraSeconds;
250 if (!$scope.isRunning) {
255 $scope.$on('timer-add-cd-seconds', function (e, extraSeconds) {
256 $timeout(function () {
257 $scope.addCDSeconds(extraSeconds);
261 $scope.$on('timer-set-countdown-seconds', function (e, countdownSeconds) {
262 if (!$scope.isRunning) {
266 $scope.countdown = countdownSeconds;
267 $scope.millis = countdownSeconds * 1000;
268 calculateTimeUnits();
273 calculateTimeUnits();
275 var tick = function tick() {
276 var typeTimer = null; // countdown or endTimeAttr
277 $scope.millis = moment().diff($scope.startTime);
278 var adjustment = $scope.millis % 1000;
280 if ($scope.endTimeAttr) {
281 typeTimer = $scope.endTimeAttr;
282 $scope.millis = moment($scope.endTime).diff(moment());
283 adjustment = $scope.interval - $scope.millis % 1000;
286 if ($scope.countdownattr) {
287 typeTimer = $scope.countdownattr;
288 $scope.millis = $scope.countdown * 1000;
291 if ($scope.millis < 0) {
294 calculateTimeUnits();
295 if($scope.finishCallback) {
296 $scope.$eval($scope.finishCallback);
300 calculateTimeUnits();
302 //We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5
303 $scope.timeoutId = setTimeout(function () {
306 }, $scope.interval - adjustment);
308 $scope.$emit('timer-tick', {timeoutId: $scope.timeoutId, millis: $scope.millis});
310 if ($scope.countdown > 0) {
313 else if ($scope.countdown <= 0) {
315 if($scope.finishCallback) {
316 $scope.$eval($scope.finishCallback);
320 if(typeTimer !== null){
321 //calculate progress bar
322 $scope.progressBar = progressBarService.calculateProgressBar($scope.startTime, $scope.millis, $scope.endTime, $scope.countdownattr);
324 if($scope.progressBar === 100){
325 $scope.displayProgressActive = ''; //No more Bootstrap active effect
330 if ($scope.autoStart === undefined || $scope.autoStart === true) {
337 /* commonjs package manager support (eg componentjs) */
338 if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
339 module.exports = timerModule;
342 var app = angular.module('timer');
344 app.factory('I18nService', function() {
346 var I18nService = function() {};
348 I18nService.prototype.language = 'en';
349 I18nService.prototype.fallback = 'en';
350 I18nService.prototype.timeHumanizer = {};
352 I18nService.prototype.init = function init(lang, fallback) {
353 var supported_languages = humanizeDuration.getSupportedLanguages();
355 this.fallback = (fallback !== undefined) ? fallback : 'en';
356 if (supported_languages.indexOf(fallback) === -1) {
357 this.fallback = 'en';
360 this.language = lang;
361 if (supported_languages.indexOf(lang) === -1) {
362 this.language = this.fallback;
366 moment.locale(this.language); //@TODO maybe to remove, it should be handle by the user's application itself, and not inside the directive
368 //human duration init, using it because momentjs does not allow accurate time (
369 // momentJS: a few moment ago, human duration : 4 seconds ago
370 this.timeHumanizer = humanizeDuration.humanizer({
371 language: this.language,
377 * get time with units from momentJS i18n
378 * @param {int} millis
379 * @returns {{millis: string, seconds: string, minutes: string, hours: string, days: string, months: string, years: string}}
381 I18nService.prototype.getTimeUnits = function getTimeUnits(millis) {
382 var diffFromAlarm = Math.round(millis/1000) * 1000; //time in milliseconds, get rid of the last 3 ms value to avoid 2.12 seconds display
386 if (typeof this.timeHumanizer != 'undefined'){
388 'millis' : this.timeHumanizer(diffFromAlarm, { units: ["milliseconds"] }),
389 'seconds' : this.timeHumanizer(diffFromAlarm, { units: ["seconds"] }),
390 'minutes' : this.timeHumanizer(diffFromAlarm, { units: ["minutes", "seconds"] }) ,
391 'hours' : this.timeHumanizer(diffFromAlarm, { units: ["hours", "minutes", "seconds"] }) ,
392 'days' : this.timeHumanizer(diffFromAlarm, { units: ["days", "hours", "minutes", "seconds"] }) ,
393 'months' : this.timeHumanizer(diffFromAlarm, { units: ["months", "days", "hours", "minutes", "seconds"] }) ,
394 'years' : this.timeHumanizer(diffFromAlarm, { units: ["years", "months", "days", "hours", "minutes", "seconds"] })
398 console.error('i18nService has not been initialized. You must call i18nService.init("en") for example');
407 var app = angular.module('timer');
409 app.factory('progressBarService', function() {
411 var ProgressBarService = function() {};
414 * calculate the remaining time in a progress bar in percentage
415 * @param {momentjs} startValue in seconds
416 * @param {integer} currentCountdown, where are we in the countdown
417 * @param {integer} remainingTime, remaining milliseconds
418 * @param {integer} endTime, end time, can be undefined
419 * @param {integer} coutdown, original coutdown value, can be undefined
421 * joke : https://www.youtube.com/watch?v=gENVB6tjq_M
422 * @return {float} 0 --> 100
424 ProgressBarService.prototype.calculateProgressBar = function calculateProgressBar(startValue, remainingTime, endTimeAttr, coutdown) {
425 var displayProgressBar = 0,
429 remainingTime = remainingTime / 1000; //seconds
432 if(endTimeAttr !== null){
433 endTimeValue = moment(endTimeAttr);
434 initialCountdown = endTimeValue.diff(startValue, 'seconds');
435 displayProgressBar = remainingTime * 100 / initialCountdown;
438 displayProgressBar = remainingTime * 100 / coutdown;
441 displayProgressBar = 100 - displayProgressBar; //To have 0 to 100 and not 100 to 0
442 displayProgressBar = Math.round(displayProgressBar * 10) / 10; //learn more why : http://stackoverflow.com/questions/588004/is-floating-point-math-broken
444 if(displayProgressBar > 100){ //security
445 displayProgressBar = 100;
448 return displayProgressBar;
451 return new ProgressBarService();