angular .module("rv.directives") .directive("bachCountdown", function ($interval) { return { controller: function ($scope, $element) { //console.log("this: ", this); var self = this; var SECONDS_MS = 1000; var MINUTES_MS = SECONDS_MS * 60; var HOURS_MS = MINUTES_MS * 60; var DAYS_MS = HOURS_MS * 24; this.timeEls = {}; this.init = function (date, days, hours, minutes, seconds) { days = parseInt(days, 10) || 0; hours = parseInt(hours, 10) || 0; minutes = parseInt(minutes, 10) || 0; seconds = parseInt(seconds, 10) || 0; if (date) { this.date = new Date(date); } else { this.date = new Date( +new Date() + (seconds * SECONDS_MS + minutes * MINUTES_MS + hours * HOURS_MS + days * DAYS_MS) ); } this.updateTime(); this.timerId = setInterval(this.updateTime, 1000); }; this.destroy = function () { clearInterval(self.timerId); }; this.updateTime = function () { var time = self.getTime(); angular.forEach(self.timeEls, function (element, key) { element.text(time[key]); }); }; this.getTime = function () { var timeDiff = self.date - Date.now(); if (timeDiff > 0) { var delta = Math.abs(timeDiff) / 1000; var days = Math.floor(delta / 86400); delta -= days * 86400; var hours = Math.floor(delta / 3600) % 24; delta -= hours * 3600; var minutes = Math.floor(delta / 60) % 60; delta -= minutes * 60; var seconds = parseInt(delta % 60, 10); return { days: days, hours: hours, minutes: minutes, seconds: seconds, }; } else { return { days: 0, hours: 0, minutes: 0, seconds: 0, }; } }; this.setTimeEl = function (type, element) { this.timeEls[type] = element; }; $scope.$on("$destroy", this.destroy); }, link: function (scope, element, attrs, ctrl) { ctrl.init( attrs.bachCountdown || attrs.bachDate, attrs.bachDays, attrs.bachHours, attrs.bachMinutes, attrs.bachSeconds ); }, }; }) .directive("bachCountdownDays", function () { return { require: "^bachCountdown", link: function (scope, element, attrs, ctrl) { ctrl.setTimeEl("days", element); }, }; }) .directive("bachCountdownHours", function () { return { require: "^bachCountdown", link: function (scope, element, attrs, ctrl) { ctrl.setTimeEl("hours", element); }, }; }) .directive("bachCountdownMinutes", function () { return { require: "^bachCountdown", link: function (scope, element, attrs, ctrl) { ctrl.setTimeEl("minutes", element); }, }; }) .directive("bachCountdownSeconds", function () { return { require: "^bachCountdown", link: function (scope, element, attrs, ctrl) { ctrl.setTimeEl("seconds", element); }, }; });