angularjs re-initialize directive - javascript

I have the following code
HTML
<countdown ng-show="vm.inhotel" init-val="vm.finishtime" init-lastmess="''" init-mess="'Sjekk ut'"></countdown>
Controller
vm.finishtime = 0;
vm.inhotel = false;
$rootScope.$on('enterhotel', function(data) {
console.log(data);
console.log("entering hotel for " + data.totime);
vm.inhotel = true;
vm.finishtime = new Date().getTime() + 60 * 60 * 24 * 1000;
});
Countdown directory
angular
.module('users')
.directive('countdown', countdown);
function getFormattedTime(secs) {
var date = new Date(null);
date.setSeconds(secs);
return date.toISOString().substr(11, 8);
}
function countdown() {
return {
restrict: 'E',
template: '<div class=\"{{class}}\" style=\"{{isfloating}} margin-right:5px;\""><span style=\"font-size:{{firstsize}}px;\">{{firstmess}}</span> <span style=\"font-size:{{initsize}}px;\">{{result}}</span></div>',
scope: {
initVal: '=',
initMess: '=',
initLastmess: '=',
initMesssize: '=',
initSize: '=',
initIsfloating: '=',
},
controller: function($scope, $interval) {
if ($scope.initIsfloating) {
$scope.isfloating = 'float:left;';
} else {
$scope.isfloating = '';
}
if ($scope.initLastmess == 'undefined') {
$scope.initLastmess = '';
}
$scope.countdownVal = $scope.initVal;
$scope.countdownVal = Math.floor($scope.countdownVal / 1000) - Math.floor(Date.now() / 1000);
var b = getFormattedTime($scope.countdownVal);
$scope.class = "";
$scope.firstsize = $scope.initMesssize;
$scope.initsize = $scope.initSize;
$scope.firstmess = $scope.initMess;
if ($scope.countdownVal > 0) {
$scope.result = b + " " + $scope.initLastmess;
} else {
$scope.class = "";
$scope.result = "00:00:00 " + $scope.initLastmess;
}
$interval(function () {
$scope.firstsize = $scope.initMesssize;
$scope.initsize = $scope.initSize;
$scope.firstmess = $scope.initMess;
if ($scope.initIsfloating) {
$scope.isfloating = 'float:left;';
} else {
$scope.isfloating = '';
}
if ($scope.initLastmess == 'undefined') {
$scope.initLastmess = '';
}
if ($scope.countdownVal > 0) {
$scope.class = "";
$scope.countdownVal = $scope.initVal;
$scope.countdownVal = ($scope.initVal / 1000) - Math.floor(Date.now() / 1000);
$scope.result = getFormattedTime($scope.countdownVal) + " " + $scope.initLastmess;
} else {
$scope.class = "";
$scope.result = " 00:00:00 " + $scope.initLastmess;
}
}, 1000);
}
}
};
but the countdown wont change the new finishtime object. is it possible to reinitialize the countdown directive to refresh it with my new countdown?

Related

How to make timer not to restart after page refresh in psgTimer library of Jquery?

This is the code snippet of psgTimer Jquery Library, I want not to reload the timer when the page refreshes. I try to save the time diff in local storage. But not able to get the result. Please provide the solution.
(function () {
var callbacks = {
onInit: function () {
},
onStart: function () {
},
onStop: function () {
},
onEnd: function () {
},
onChangeStart: function () {
},
onChangeEnd: function () {
}
};
var base = {
stopped: true,
timezone: 0,
diff: null,
isEnd: false
};
var PsgTimer = function (selector, options) {
var timer = this;
if (selector.nodeType === Node.ELEMENT_NODE) {
timer.container = $(selector);
} else if (typeof selector === 'string') {
timer.selector = selector;
timer.container = $(timer.selector);
} else if (typeof selector === 'object') {
options = selector;
timer.selector = options.selector;
timer.container = $(timer.selector);
}
timer.options = $.extend({}, {
selector: '#psgTimer',
animation: false,
multipleBlocks: false,
endDateTime: undefined,
// currentDateTime: window.serverTime['U'] * 1000 || Date.now(),
currentDateTime: Date.now(),
labels: {
days: timer.container.attr('data-label-days') ? timer.container.attr('data-label-days') : false,
hours: timer.container.attr('data-label-hours') ? timer.container.attr('data-label-hours') : false,
minutes: timer.container.attr('data-label-minutes') ? timer.container.attr('data-label-minutes') : false,
seconds: timer.container.attr('data-label-seconds') ? timer.container.attr('data-label-seconds') : false
}
}, options);
timer.callbacks = timer.options.callbacks = $.extend({}, callbacks, timer.options.callbacks);
timer.base = $.extend({}, base);
if (typeof timer.options.endDateTime === 'string') {
timer.options.endDateTime = setTimerEndFromString(timer, timer.options.endDateTime);
}
timer.container.length ? timer.init() : console.log('No timer element on this page');
};
PsgTimer.prototype.init = function () {
var timer = this,
options = this.options;
var timerEnd = timer.container.attr('data-timer-end');
if (timerEnd !== undefined) {
options.endDateTime = setTimerEndFromString(timer, timerEnd);
}
// options.endDateTime = options.endDateTime + (timer.base.timezone * 1000 * 60 * 60);
timer.countdown = transformCountToArray(getCurrentCountDown(timer), options.multilpeBlocks);
timer.container.addClass('psgTimer').append(createMarkup(timer));
if (options.animation) {
timer.container.addClass('psgTimer_' + options.animation);
}
timer.query = setQueries(timer);
timer.callbacks.onInit();
if (!timer.base.isEnd) {
timer.start();
}
};
PsgTimer.prototype.start = function () {
var timer = this;
if (timer.base.stopped) {
timer.base.stopped = false;
timer.intervalId = setInterval(function () {
updateCounter(timer);
}, 1000);
timer.callbacks.onStart();
}
};
PsgTimer.prototype.restart = function () {
var timer = this;
timer.options.currentDateTime = Date.now();
timer.start();
};
PsgTimer.prototype.stop = function () {
var timer = this;
timer.base.stopped = true;
clearTimeout(timer.intervalId);
timer.callbacks.onStop();
};
var getCurrentCountDown = function (timer) {
var options = timer.options;
var base = timer.base;
options.currentDateTime = options.currentDateTime + 1001;
base.diff = options.endDateTime - options.currentDateTime;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
if (base.diff > 0) {
var total = parseFloat(((((base.diff / 1000.0) / 60.0) / 60.0) / 24.0));
days = parseInt(total);
total -= days;
total *= 24.0;
hours = parseInt(total);
total -= hours;
total *= 60.0;
minutes = parseInt(total);
total -= minutes;
total *= 60;
seconds = parseInt(total);
} else {
timer.callbacks.onEnd();
timer.stop();
timer.base.isEnd = true;
}
return {
days: {
amount: days,
max: Infinity,
className: 'days'
},
hours: {
amount: hours,
max: 24,
className: 'hours'
},
minutes: {
amount: minutes,
max: 60,
className: 'minutes'
},
seconds: {
amount: seconds,
max: 60,
className: 'seconds'
}
}
};
var transformCountToArray = function (count, multilpeBlocks) {
if (typeof count === 'object') {
for (var unit in count) {
if (count.hasOwnProperty(unit)) {
count[unit].amount = count[unit].amount.toString();
if (count[unit].amount.length < 2) {
count[unit].amount = '0' + count[unit].amount;
}
if (multilpeBlocks) {
count[unit].amount = count[unit].amount.split('');
} else {
count[unit].amount = [count[unit].amount];
}
}
}
}
return count;
};
var getTimeZone = function (string) {
var hours, minutes;
var number = string.replace(/\D/g, '');
var digit = string.replace(/[^+-]/g, '');
var multiplier = digit === '-' ? (-1) : 1;
if (number.length >= 3) {
hours = Number(number.substr(0, number.length - 2));
minutes = Number(number.substr(number.length - 2, 2));
} else {
hours = Number(number);
minutes = 0;
}
return (hours + minutes/60) * multiplier;
};
var setTimerEndFromString = function (timer, endTimeString) {
var timerDate = {};
var timerEnd = endTimeString.split(' ');
var endTime;
var timeExp = /^([0-1]\d|2[0-3])(:[0-5]\d){1,2}$/;
var dateExp = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
var zoneExp = /(UTC|GMT)[+-](\d{1,2}([:,.]?\d{2})?)/;
for (var i = 0; i < timerEnd.length; i++) {
if (timerEnd[i].match(timeExp)) {
timerDate.time = timerEnd[i].split(':');
} else if (timerEnd[i].match(dateExp)) {
timerDate.date = timerEnd[i].split('.');
} else if (timerEnd[i].match(zoneExp)) {
timer.base.timezone = getTimeZone(timerEnd[i]);
} else {
console.log('Wrong end time.');
}
}
timerDate.year = parseInt(timerDate.date[2]) || 0;
timerDate.month = parseInt(timerDate.date[1]) - 1 || 0;
timerDate.day = parseInt(timerDate.date[0]) || 0;
timerDate.hours = parseInt(timerDate.time[0]) || 0;
timerDate.minutes = parseInt(timerDate.time[1]) || 0;
timerDate.seconds = parseInt(timerDate.time[2]) || 0;
timerDate.miliseconds = parseInt(timerDate.time[3]) || 0;
endTime = Date.UTC(timerDate.year, timerDate.month, timerDate.day, timerDate.hours, timerDate.minutes, timerDate.seconds, timerDate.miliseconds);
return endTime;
};
var createMarkup = function (timer) {
var countdown = timer.countdown;
var markup = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
var numberBlocks = '';
countdown[unit].amount.forEach(function (num) {
numberBlocks += numberContainer(timer, num);
});
markup.unit += '<div class="' + countdown[unit].className + ' psgTimer_unit">' + numberBlocks + '</div>';
}
}
markup.numbers = '<div class="psgTimer_numbers">' + markup.unit + '</div>';
markup.full = markup.numbers;
if (
timer.options.labels &&
timer.options.labels.days &&
timer.options.labels.hours &&
timer.options.labels.minutes &&
timer.options.labels.seconds
) {
var labels = timer.options.labels;
markup.labels = '<div class="psgTimer_labels">' +
'<div class="days">' + labels.days + '</div>' +
'<div class="hours">' + labels.hours + '</div>' +
'<div class="minutes">' + labels.minutes + '</div>' +
'<div class="seconds">' + labels.seconds + '</div>' +
'</div>';
markup.full = markup.numbers + markup.labels;
} else {
markup.full = markup.numbers;
}
return markup.full;
};
var numberContainer = function (timer, num) {
var markup = '',
data = 'data-number="' + num + '"';
var numberBlock = '<div class="number" ' + data + '>' + num + '</div>';
if (timer.options.animation === 'fade') {
markup = '<div>' + numberBlock + '</div>';
} else {
markup = numberBlock;
}
return markup;
};
var setQueries = function (timer) {
var countdown = timer.countdown,
query = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
query[unit] = timer.container.find(numberSelector(timer, countdown[unit].className));
}
}
return query;
};
var numberSelector = function (timer, className) {
var selector = '';
if (timer.options.animation === 'fade') {
selector = '.' + className + ' .number';
} else {
selector = '.' + className + ' .number';
}
return selector;
};
var updateCounter = function (timer) {
timer.callbacks.onChangeStart();
timer.countdown = transformCountToArray(getCurrentCountDown(timer), timer.options.multilpeBlocks);
for (var unit in timer.countdown) {
if (timer.countdown.hasOwnProperty(unit)) {
timer.countdown[unit].amount.forEach(function (number, index) {
if (timer.query[unit][index].getAttribute('data-number') !== number) {
aminate(timer.query[unit][index], number, timer.options.animation);
}
});
}
}
timer.callbacks.onChangeEnd();
};
var aminate = function (el, value, animationType) {
var $el = $(el);
$el.attr('data-number', value);
if (animationType === 'fade') {
animation.fade($el, value);
} else {
$el.html(value);
}
};
var animation = {
fade: function ($el, value) {
var animDuration = 350;
$el.css({
'transition': 'opacity ' + animDuration + 'ms',
'opacity': '0'
});
setTimeout(function () {
$el.html(value).css('opacity', 1);
}, animDuration + 10);
}
};
window.PsgTimer = PsgTimer;
})();
.psgTimer{display:table;margin:0 auto 30px auto;font-size:0;font-family:'Roboto', sans-serif}.psgTimer_numbers>div,.psgTimer_labels>div{display:inline-block;font-size:0;width:124px;text-align:center}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{content:":";line-height:60px;height:60px;display:block;font-weight:bold;font-size:24px;color:#21272C;position:absolute;top:0;right:-4px}.psgTimer_numbers>div:last-child:after{content:none}.psgTimer_numbers>div>div{display:inline-block;vertical-align:top;width:44px;height:60px;line-height:60px;background:#21272C;box-shadow:0px 4px 8px rgba(0,0,0,0.2);border-radius:6px;font-weight:bold;font-size:24px;text-align:center;color:#FFD631}.psgTimer_numbers>div>div:first-child{margin-right:5px}.psgTimer_labels>div{padding-top:5px !important;font-size:12px;line-height:18px;text-transform:uppercase;letter-spacing:1.2px;color:#21272C}#media screen and (max-width: 640px){.psgTimer_numbers>div,.psgTimer_labels>div{width:74px}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{line-height:40px;height:40px;font-size:16px;right:-2px}.psgTimer_numbers>div div{width:26px;height:40px;line-height:40px;font-size:16px}.psgTimer_numbers>div div:first-child{margin-right:2px}.psgTimer_labels>div{font-size:10px;line-height:16px}}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div id="firstTimer"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var timer = new PsgTimer({
selector: '#firstTimer',
currentDateTime: Date.UTC(2018, 0, 26, 12, 0, 0),
endDateTime: Date.UTC(2018, 0, 26, 12, 5, 0),
multilpeBlocks: true,
animation: 'fade',
labels: {
days: 'Days',
hours: 'Hours',
minutes: 'minutes',
seconds: 'seconds'
},
callbacks: {
onInit: function () {
console.log('Hello world!');
}
}
});
})
</script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
</body>
</html>
You can take the reference from psgTimer library
https://www.jqueryscript.net/time-clock/psg-countdown-timer.html

Timer not binding DOM value in AngularJS

I'm a backend developer, who's trying hard to make a timer by comparing two different date formats. This part of the script is working great, but whenever I try to make recursive call, nothing is binding.
I almost tried everything, from passing it into a function, using the $interval, the setInterval, and on and on. The main reason is I cannot get the value of its loop, and binding into my DOM.
Here is some of my code. Here I set all variables for the countDown() function.
$scope.timer.list = {};
$scope.timer.date = new Date();
$scope.timer.list.D = '00';
$scope.timer.list.M = '00';
$scope.timer.list.Y = '00';
$scope.timer.list.h = '00';
$scope.timer.list.m = '00';
$scope.timer.list.s = '00';
$scope.begin = {};
$scope.begin.date = {};
$scope.begin.timer = {};
$scope.counter = {
show : false,
text : '00:00'
};
setInterval(function() {
$scope.obj = {
show : $scope.countDown($scope.privateshowcase.begin_at).show,
text : $scope.countDown($scope.privateshowcase.begin_at).text
}
$scope.counter = $scope.obj;
}, 1000);
Then, here is the function:
$scope.countDown = function(begin) {
$scope.timer.date = new Date();
$scope.timer.list.D = $filter('date')($scope.timer.date, 'dd');
$scope.timer.list.M = $filter('date')($scope.timer.date, 'MM');
$scope.timer.list.Y = $filter('date')($scope.timer.date, 'yyyy');
$scope.timer.list.h = $filter('date')($scope.timer.date, 'HH');
$scope.timer.list.m = $filter('date')($scope.timer.date, 'mm');
$scope.timer.list.s = $filter('date')($scope.timer.date, 'ss');
$scope.begin.full = begin.split(" ");
$scope.begin.date = $scope.begin.full[0].split("-");
$scope.begin.timer = $scope.begin.full[1].split(":");
$scope.begin.D = $scope.begin.date[2];
$scope.begin.M = $scope.begin.date[1];
$scope.begin.Y = $scope.begin.date[0];
$scope.begin.h = $scope.begin.timer[0];
$scope.begin.m = $scope.begin.timer[1];
$scope.begin.s = $scope.begin.timer[2];
if($scope.timer.list.Y == $scope.begin.Y) {
if($scope.timer.list.M == $scope.begin.M) {
if($scope.timer.list.D == $scope.begin.D) {
$scope.counter.diff_h = $scope.timer.list.h - $scope.begin.h;
if($scope.counter.diff_h == 0 || $scope.counter.diff_h == -1) {
if($scope.counter.diff_h == 0) {
if($scope.timer.list.m > $scope.begin.m) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if ($scope.timer.list.m <= $scope.begin.m) {
$scope.counter.show = true;
$scope.counter.diff_m = $scope.begin.m - $scope.timer.list.m;
if($scope.counter.diff_m <= 30) {
$scope.counter.diff_s = 60 - $scope.timer.list.s;
if($scope.counter.diff_s == 60) {
$scope.counter.s = "00";
$scope.counter.diff_m_f = $scope.counter.diff_m + 1;
} else if($scope.counter.diff_s >= 1 && $scope.counter.diff_s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
}
if($scope.counter.diff_m_f >= 1 && $scope.counter.diff_m_f <= 9) {
$scope.counter.m = "0" + $scope.counter.diff_m_f;
} else {
$scope.counter.m = $scope.counter.diff_m_f;
}
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else if ($scope.counter.diff_h == -1) {
$scope.counter.diff_timer = $scope.timer.m - 60;
$scope.counter.diff_m = $scope.begin.m - $scope.counter.diff_timer;
if($scope.counter.diff_m > 30) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if($scope.counter.diff_m <= 30) {
$scope.counter.show = true;
$scope.counter.diff_timer_s = $scope.timer.s - 60;
if($scope.counter.diff_timer_s == 60) {
$scope.counter.s = "00";
$scope.counter.m = $scope.counter.diff_m + 1;
} else if($scope.counter.s >= 1 && $scope.counter.s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
return $scope.counter = {
show : $scope.counter.show,
text : $scope.counter.text
};
}
'begin' is : 'YYYY/MM/DAY HH:MM:SS'
Maybe my way of thinking is not the good one, but at list I have a very functional timer, which replace every 1 to 9 into 01 to 09, convert the 60 into 00, can compare 2 different hours.
I think you are over complicating things a little bit. I came up with a simple countDown component made in angularjs 1.6.0 (it can be done with directives for angularjs older versions as well) that compares an input Date with the now Date.
You can play around with the input and change dates to see changes happen on the component, as long as you don't break the date format.
Note on dates: simple way to compare dates:
var date0 = new Date("2017-09-12T14:45:00.640Z");
var date1 = new Date("2017-09-13T14:45:00.640Z");
var dateDiff = new Date(date1.getTime() - date0.getTime());
// "1970-01-02T00:00:00.000Z"
Although dateDiff looks weird, it's basically one day from the zero date 1970-01-01T00:00:00.000Z.
Given that, you just let angularjs do the magic (or maybe trick).
{{ dateDiff | date:"d \'days\' hh:mm:ss" }}
Besides, if you don't want to work with dates in the natural form of javascript, you can use angularjs-moment which provide you date and time utility from momentjs regardless of javascript dates pitfalls.
Here is the working code:
angular
.module('app', [])
.run(function($rootScope) {
$rootScope.countDownToDate = new Date().addDays(2);
})
.component('countDown', {
template: '{{ $ctrl.timer | date:"d \'days\' hh:mm:ss" }}',
bindings: {
to: '<'
},
controller: function CountDownCtrl($interval) {
var $this = this;
this.$onInit = function() {
$interval($this.setTime, 1000);
};
$this.setTime = function() {
$this.timer = new Date(new Date($this.to).getTime() - new Date().getTime());
}
}
});
// bootstrap the app
angular.element(function() {
angular.bootstrap(document, ['app']);
});
// extension to add days on date
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<div>
<center>
<h1>
<count-down to="countDownToDate" />
</h1>
<label for="countDownToDate">To Date</label>
<input type="datetime" name="countDownToDate" ng-model="countDownToDate">
</center>
</div>

How to identify the specific Interval in angular js to destroy

Below directive is used for getting data continuously from server with default interval of 5 sec
app.directive('livestatDataGrid', livestatDataGrid);
function livestatDataGrid($http, $interval, $window) {
return {
restrict: 'E',
templateUrl: 'directives/livestatDataGrid/livestat-datagrid.html',
scope: {
viewName: '=viewName',
gridOptions: '=',
deleteItem: '=deleteItem'
},
link: function($scope) {
var defaultSec = 5;
$scope.timerObj = {};
$scope.timerObj.selectedItem = defaultSec;
$scope.timerObj.isDisplay = true;
var timer = null;
$scope.copyVal = defaultSec;
$scope.getViewData = function(viewName) {
console.log('Came here !! Directive ', viewName);
$http.get('json/' + viewName + '.json').then(function success(response) {
$scope.metricHeader = response.data.metricHeader;
$scope.stats = response.data.stats;
}, function error(error) {
console.log("Eooor ", error)
});
};
$scope.getViewData($scope.viewName);
// Timer code
$scope.editTimer = function() {
$scope.timerObj.isDisplay = false;
};
$scope.setTimer = function() {
if ($scope.timerObj.selectedItem && isNaN($scope.timerObj.selectedItem)) {
$scope.timerObj.selectedItem = defaultSec;
}
if ($scope.copyVal != "" && $scope.copyVal == $scope.timerObj.selectedItem) {
$scope.timerObj.isDisplay = true;
return;
}
$scope.StopTimer();
$scope.copyVal = angular.copy($scope.timerObj.selectedItem);
$scope.timerObj.isDisplay = true;
$scope.startTimer();
};
// starting the timer here once directive is initialized.Using `$interval`
$scope.startTimer = function() {
console.log("in timer " + $scope.timerObj.selectedItem);
if ($scope.timerObj.selectedItem && $scope.viewName) {
//time interval for sending request to server
timer = $interval(function() {
if ($scope.viewName)
$scope.getViewData($scope.viewName);
$interval.cancel(this);
console.log(timer)
}, $scope.timerObj.selectedItem * 1000);
}
};
$scope.startTimer();
// Once the job is done, destroy the timer using `$interval.cancel`.
$scope.StopTimer = function() {
if (angular.isDefined(timer)) {
console.log("in stop timer");
$interval.cancel(timer);
}
};
//timer code ends her
}
}
}
Not clear what do you intend to ask/discuss. Is this a self answer question?

AngularJS difference between 2 dates

I have an APP(The app is built using springboot for the API and AngularJs for the view.) that gets a report for when an incidente started and finished, startdate(2015-12-01T08:19:00.000Z) and enddate(2015-12-06T02:59:00.000Z) as examples.
I dont seem to find a good way to set the difference between the two dates to a new value unavailability.
This is my .js file:
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
'urlinc',
'$location',
function($scope, $http, $routeParams, urlinc, $location) {
var url = urlinc.getUrlinc();
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
var onHardwareComplete = function(response) {
$scope.hardwares = response.data;
};
var onSoftwareComplete = function(response) {
$scope.softwares = response.data;
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(url + code)
.then(onIncidenteComplete, onError);
$http.get("http://localhost:8080/tecnico/").then(
onTecnicoComplete);
$http.get("http://localhost:8080/hardware/").then(
onHardwareComplete);
$http.get("http://localhost:8080/software/").then(
onSoftwareComplete);
$http.get("http://localhost:8080/sistema/").then(
onSistemaComplete);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(url, incidente).success(
function(data, status, headers, config) {
var status2 = '/' + status + '/';
$location.url(status2);
return status.data;
}).error(function(status) {
var status2 = '/' + status.status + '/';
console.log(status2);
$location.url(status2);
return status.data;
})
};
$scope.hardwares = [];
$scope.hardwareListener = function() {
console.log($scope.hardwares);
}
$scope.tecnicoListener = function() {
console.log($scope.incidente.tecnico);
}
$scope.date = new Date();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
var that = this;
this.dates = {
apertura: new Date(),
cierre: new Date(),
};
this.open = {
apertura: false,
cierre: false,
};
// Disable weekend selection
this.disabled = function(date, mode) {
return (mode === 'day' && (new Date().toDateString() == date.toDateString()));
};
this.dateOptions = {
showWeeks: false,
startingDay: 1
};
this.timeOptions = {
readonlyInput: false,
showMeridian: false
};
this.dateModeOptions = {
minMode: 'year',
maxMode: 'year'
};
this.openCalendar = function(e, date) {
that.open[date] = true;
};
// watch date1 and date2 to calculate difference
this.calculateWatch = $scope.$watch(function() {
return that.dates;
}, function() {
if (that.dates.apertura && that.dates.cierre) {
var diff = that.dates.apertura.getTime() - that.dates.cierre.getTime();
that.dayRange = Math.round(Math.abs(diff/(1000*60*60*24)))
} else {
that.dayRange = 'n/a';
}
}, true);
$scope.$on('$destroy', function() {
that.calculateWatch();
});
} ])
EDIT : This is how i managed to make it work:
$scope.calcularIndisponibilidad = function(incidente){
var cierre = incidente.cierre;
var apertura = incidente.apertura;
var date1 = Date.parse(cierre);
var date2 = Date.parse(apertura);
var difference = date1 - date2;
console.log(difference);
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var indisponibilidad = 'difference = ' + daysDifference + ' day/s ' + hoursDifference + ' hour/s ' + minutesDifference + ' minute/s ';
console.log(indisponibilidad);
I would suggest two ways
1. Manually calcuating
Answered before Calculate difference between 2 timestamps using javascript
2. Using Moment.js
moment().format('MMMM Do YYYY, h:mm:ss a'); // December 15th 2015, 11:14:37 am

Variable coming back undefined into the same scope in AngularJS

Given the following code, I'm finding that once the loadDetails function (the last one) is being triggered, the ID variable comes back undefined, as on the other functions is coming back correctly.
Did I miss something?
function Ctrl($scope, $http) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=7', {ignoreLoadingBar: true}).
success(function(data3) {
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
}
}
$scope.$watch('name', search, true);
$scope.getDetails = function (id) {
$http.get('http://api.discogs.com/artists/' + id).
success(function(data) {
$scope.artist = data;
});
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=8').
success(function(data2) {
$scope.releases = data2.releases;
});
$scope.$watch(function() {
return $scope.artist;
}, function() {
var pos = $scope.artist.name.toLowerCase().indexOf(', the');
if (pos != -1) {
$scope.artist.name = 'The ' + $scope.artist.name.slice(0, pos);
}
});
var _page = 0;
$scope.releases = [];
$scope.loadDetails = function(id) {
_page++;
console.log(_page);
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=' + _page + '&per_page=12').then(function(data2) {
$scope.releases = data2.releases;
});
};
$scope.clicked = true;
$scope.sliding = true;
}
EDIT: Here's my view code:
<div class="infinite" infinite-scroll="loadDetails(artist.id)">
<div class="col-xs-3 col-md-3 release" ng-controller="ImageCtrl" release="release" ng-repeat="release in releases | filter:album | filter:year" the-directive position="{{ $index + 1 }}" last="{{ $last }}">
<img class="img-responsive" ng-src="{{image}}"/> {{release.title | characters:45}}
</div>
<div style='clear: both;'></div>
</div>
And the ng-Infinite-Scroll script that triggers the function when the containing div reaches the bottom:
/* ng-infinite-scroll - v1.0.0 - 2013-02-23 */
var mod;
mod = angular.module('infinite-scroll', []);
mod.directive('infiniteScroll', [
'$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) {
return {
link: function(scope, elem, attrs) {
var checkWhenEnabled, handler, scrollDistance, scrollEnabled;
$window = angular.element($window);
scrollDistance = 0;
if (attrs.infiniteScrollDistance != null) {
scope.$watch(attrs.infiniteScrollDistance, function(value) {
return scrollDistance = parseInt(value, 10);
});
}
scrollEnabled = true;
checkWhenEnabled = false;
if (attrs.infiniteScrollDisabled != null) {
scope.$watch(attrs.infiniteScrollDisabled, function(value) {
scrollEnabled = !value;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return handler();
}
});
}
handler = function() {
var elementBottom, remaining, shouldScroll, windowBottom;
windowBottom = $window.height() + $window.scrollTop();
elementBottom = elem.offset().top + elem.height();
remaining = elementBottom - windowBottom;
shouldScroll = remaining <= $window.height() * scrollDistance;
if (shouldScroll && scrollEnabled) {
if ($rootScope.$$phase) {
return scope.$eval(attrs.infiniteScroll);
} else {
return scope.$apply(attrs.infiniteScroll);
}
} else if (shouldScroll) {
return checkWhenEnabled = true;
}
};
$window.on('scroll', handler);
scope.$on('$destroy', function() {
return $window.off('scroll', handler);
});
return $timeout((function() {
if (attrs.infiniteScrollImmediateCheck) {
if (scope.$eval(attrs.infiniteScrollImmediateCheck)) {
return handler();
}
} else {
return handler();
}
}), 0);
}
};
}
]);
rSo from what I read I understand you problem as in loadDetails() the id parameter is undefined. Where is loadDetails() called from? I assume its being called from the view. Are you passing this param in when it is being called? For ex:
<button ng-click="loadDetails('myId')">Load Details</button>
I would say your issue is you are not passing the param to this function. It would be helpful if you posted the view associated with this controller.

Categories