24 hr countdown loop in angular js - angularjs

Hello am just knew to angular, how can you translate this code into angularjs. My goal is to have it count down 24hrs and restarts again
setInterval(function time(){
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
jQuery('#the-final-countdown p').html(hours+':'+min+':'+sec)
}, 1000);
This is the html
<div id="the-final-countdown">
<p></p>
</div>

Just wrap the funciton setInterval into $interval in your controller like this:
$interval(function time(){
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
$scope.data = hours+':'+min+':'+sec;
}, 1000);
and in your view just template with data like this
<p>{{data}}</p>

Related

Angularjs: automatically update date diff?

I'm using angular 1.6.1 and I would like to update date diff automatically.
Here is the service that calculate date diff
angular.module("utils", [])
.service('utils', function ($location) {
this.correctDate = function(date) {
var s = date.replace('T', ' ');
return s.replace('.000Z', ' ');
}
this.dateDiff = function(date) {
var oneMinute = 60*1000;
var oneHour = 60*60*1000;
var oneDay = 24*60*60*1000;
var oneWeek = 24*60*60*1000*7;
var oneMonth = 24*60*60*1000*30;
var now = new Date();
var d = new Date(date);
var tNow = now.getTime();
var tDate = d.getTime();
if((tNow - tDate) / oneMonth >= 1){
return Math.floor((tNow - tDate) / oneMonth) + " months";
}
if((tNow - tDate) / oneDay >= 1){
return Math.floor((tNow - tDate) / oneDay) + " days";
}
if((tNow - tDate) / oneHour >= 1){
return Math.floor((tNow - tDate) / oneHour) + " hours";
}
if((tNow - tDate) / oneMinute >= 1){
return Math.floor((tNow - tDate) / oneMinute) + " minutes";
}
return "now";
}
})
Here is the view
<div class="post__date">
<time class="published">
{{dateDiff(correctDate(article.createdAt))}}
</time>
</div>
Now date diff is updated only if I make a click anywhere in app and I even don't understand why. So I have 2 questions :
1) Why does date diff is updated everytime I click anywhere in my angular app ? (Does angular trigger a full digest everytime I click anywhere in app ?)
2) How to update automatically date diff ?

split time between start time and end time for user given minutes as input

In my app I have a drop-down for booking an appointment with psychiatrist. Here the user gives the input as minutes, to talk to the doctor,so in drop-down it should look like a normal timings like 9-10 am, 10-11pm so on till 5pm, so the customer can see the available timing to book the appointment. I'm struggling to get this time split. I have done only the conversion from mins to hours and after that Im struck with the time split.Hoping for some help here, or any valid guidance for proceeding to get the time split.
Controller:
myApp.controller('ctrl', function ($scope) {
$scope.calc = function () {
var time = $scope.timeSelect;
if (time < 60) {
var a = (time) + 'm';
} else if (time % 60 == 0) {
var a = (time - time % 60) / 60 + 'h';
} else {
var a = ((time - time % 60) / 60 + 'h' + ' ' + time % 60 + 'm');
}
$scope.result =a;
}
$scope.result='';
});
Whenever you are dealing with dates and times I highly recommend using Momentj.js. Here is an extremely contrived example to demonstrate how you might use Moment.js to set your time periods.
angular.module("app", ["angularMoment"])
.controller("ctrl", function($scope, moment) {
var startingTime = moment().hours(9).minutes(0);
var endingTime = moment().hours(17).minutes(0);
$scope.selectedTimeslot = "";
$scope.intervals = [15, 30, 45, 60, 90, 120];
$scope.interval = 60;
$scope.timeslots = [];
$scope.setTimeSlots = function() {
$scope.timeslots = [];
var currentStartTime = angular.copy(startingTime); // use copy to avoid reference issues since we're dealing with objects and not primitives
while (currentStartTime < endingTime) {
$scope.timeslots.push(currentStartTime.format("h:mm") + " - " + currentStartTime.add($scope.interval, "minute").format("h:mm"));
}
}
$scope.setTimeSlots();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.0/angular-moment.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
Interval in minutes: <select ng-model="interval" ng-change="setTimeSlots()" ng-options="i for i in intervals"></select>
<br/>Timeslots:
<select ng-model="selectedTimeslot" ng-options="slot for slot in timeslots">
<option value="">Please select</option>
</select><br/><br/>
Selected timeslot: {{selectedTimeslot}}
</div>
This might work for you:
function createTimeSlots(startHour, endHour, interval) {
if (!startHour) {
endHour = 8;
}
if (!endHour) {
endHour = 20;
}
var timeSlots = [],
dateTime = new Date(),
timeStr = '';
dateTime.setHours(startHour, 0, 0, 0);
while (new Date(dateTime.getTime() + interval * 60000).getHours() < endHour) {
timeStr = dateTime.getHours() + ':' + dateTime.getMinutes();
timeStr += '-';
dateTime = new Date(dateTime.getTime() + interval * 60000);
timeStr += dateTime.getHours() + ':' + dateTime.getMinutes();
timeSlots.push(timeStr);
}
return timeSlots;
}
console.log(createTimeSlots(9, 18, 45));
"9:0-9:45",
"9:45-10:30",
"10:30-11:15",
"11:15-12:0",
"12:0-12:45",
"12:45-13:30",
"13:30-14:15",
"14:15-15:0",
"15:0-15:45",
"15:45-16:30",
"16:30-17:15"
You might wanna add some 0 padding on the getHours() and getMinutes() so that 1:0 will be printed as 01:00.
From the question I get a rough idea of what you need, so I hope this helps you on your way. First, I would make a separate function to convert a time (in number of minutes from midnight, as an easy example) to a string, like this:
function timeToString(time) {
if (time < 12 * 60)
return (time - time % 60) / 60 + ":" + time % 60 + "am";
else return (time - time % 60 - 12*60) / 60 + ":" + time % 60 + "pm";
}
Then the array to fill the drop-down can be created like this:
var times = [];
for (t = startHour * 60; t < endHour * 60; t += duration) {
times[times.length] = timeToString(t) + ' - ' + timeToString(t + duration);
}

If element exists by data attribute

I have a number of spans being created with ng-repeat:
<div class="row" id="year-1">
<span class="event" ng-repeat="(key, event) in events" event data-start={{event.date_start}} data-end={{event.date_end}} data-key={{key}} data-type={{event.role}}>
{{event.title}} - {{event.date_start}}
</span>
</div>
I have a directive for event which does a number of things to manipulate each span created accordingly. One of the things is to check is there are other spans with data-type="X".
In my directive, if I do the following, I get all the span's with class 'event':
var parentid = angular.element(document.getElementById('year-1'));
var typeExists = parentid[0].querySelectorAll('.event')[0];
But if I try to narrow it down to data-type="X" such as the following, I get undefined.
var typeExists = parentid[0].querySelectorAll('.event[data-type="' + attr.type + '"]')[0];
Am I overlooking something? Full directive:
angular.module("app").directive("event", function() {
return {
link: function(scope, element, attr) {
var getStart = attr.start.split('-'),
getEnd = attr.end.split('-'),
getKey = attr.key;
getHeight = element[0].offsetHeight;
var parentid = angular.element(document.getElementById('year-1')),
backgroundParent = angular.element(document.getElementsByClassName('year-current'));
// get the month event starts with
var monthStart = angular.element(document.querySelectorAll('[data-location="' + getStart[1] + '"]'));
// get the month event ends with
var monthEnd = angular.element(document.querySelectorAll('[data-location="' + getEnd[1] + '"]'));
// how many events do we have
var eventcount = angular.element(document.getElementsByClassName('event'));
// get width of events container
var eventsContainer = angular.element(document.getElementById('events'));
// does this type exist already, if so get its top
var typeExists = parentid[0].querySelectorAll('.event')[0];
console.log(typeExists);
if(monthStart.length > 0) {
// how many days in start month
var daysStart = getDaysInMonth(getStart[1], getStart[0]),
daysStartPercent = (getStart[2] / daysStart.length);
// how many days in end month
var daysEnd = getDaysInMonth(getEnd[1], getEnd[0]),
daysEndPercent = (getEnd[2] / daysEnd.length);
// determine left starting %
var elementLeft = ((monthStart[0].offsetLeft + (monthStart[0].clientWidth * daysStartPercent)) / eventsContainer[0].clientWidth) * 100;
// determine width in %
var elementRight = ((monthEnd[0].offsetLeft + (monthEnd[0].clientWidth * daysEndPercent)) / eventsContainer[0].clientWidth) * 100;
var width = (elementRight - elementLeft);
// get the background color for this role
var background = angular.element(document.querySelector('.role[data-type="' + attr.type + '"]'))[0].getAttribute('data-background');
element.css({
'left': elementLeft + '%',
'top' : parentid[0].offsetHeight + 'px',
'width': width + '%',
'background': background
});
element.addClass('stretchRight');
parentid.css({'height': parentid[0].offsetHeight + getHeight + 'px'});
backgroundParent.css({'height': parentid[0].offsetHeight + getHeight + 'px'});
} else {
element.css({ 'display': 'none' });
}
}
}
});
I was able to recreate the problem you saw and found that you need to change your line from this:
var typeExists = parentid[0].querySelectorAll('.event[data-type="' + attr.type + '"]')[0];
to this:
var typeExists = parentid.querySelectorAll('.event[data-type="' + attr.type + '"]')[0];
Remove the [0] from your parentid reference because you only have a single element with ID of year-1 which means it's not an array.

How to select a week with date picker

I'm using angular bootstrap datepicker. i have only one datepicker and need to select week(sunday to saturday) not day of week
for ex,
Select Week period from popup calender .
Select week period 19 July, 2015 to 25 July, 2015
Here comes output as 07/19/2015 To 07/25/2015
in jQuery, i know how to do it, jQuery weekpicker . I am curious how to select week using AngularJS
I would be grateful for any assistance.
Thanks.
Calculate week from date picker, you can try this one
$('#date').datepicker({onSelect: function() {
var mon = $(this).datepicker('getDate');
mon.setDate(mon.getDate() + 1 - (mon.getDay() || 7));
var sun = new Date(mon.getTime());
sun.setDate(sun.getDate() + 6);
alert(mon + ' ' + sun);
}});
See from this link - https://forum.jquery.com/topic/datepicker-select-week
Thanks Afroza Yasmin :-)
Finally, i got it
Please see the source How the select week with pick viewer
angular.module('app', ['ui.bootstrap']).controller("BodyCtrl", function($scope) { $scope.formData = {}; $scope.data = {};$scope.dateOptions = {
formatYear: 'yy',
startingDay: 0,
showWeeks:'false'};$scope.$watch('formData.dueDate',function(dateVal){
var weekYear = getWeekNumber(dateVal);
var year = weekYear[0];
var week = weekYear[1];
if(angular.isDefined(week) && angular.isDefined(year)){
var startDate = getStartDateOfWeek(week, year);
}
var weekPeriod = getStartDateOfWeek(week, year);
if(weekPeriod[0] != 'NaN/NaN/NaN' && weekPeriod[1] != 'NaN/NaN/NaN'){
$scope.formData.dueDate = weekPeriod[0] + " to "+ weekPeriod[1];
}
});
function getStartDateOfWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay());
else
ISOweekStart.setDate(simple.getDate() + 7 - simple.getDay());
var ISOweekEnd = new Date(ISOweekStart);
ISOweekEnd.setDate(ISOweekEnd.getDate() + 6);
ISOweekStart = ISOweekStart.getDate()+'/'+(ISOweekStart.getMonth()+1)+'/'+ISOweekStart.getFullYear();
ISOweekEnd = ISOweekEnd.getDate()+'/'+(ISOweekEnd.getMonth()+1)+'/'+ISOweekEnd.getFullYear();
return [ISOweekStart, ISOweekEnd];
}
function getWeekNumber(d) {
d = new Date(+d);
d.setHours(0,0,0);
d.setDate(d.getDate() + 4 - (d.getDay()||7));
var yearStart = new Date(d.getFullYear(),0,1);
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
return [d.getFullYear(), weekNo];
}
});
Thanks all

Calculate age from given year in AngularJS

I'm new for AngularJs. I have to calculate age from give year. How I can in PHP?
My script and view files are following,
My .Js:
function mycontroller($scope){
$scope.sales = [
{
name: 'steptoinstall',
year: 1986,
}
]; }
My view.php:
<li ng-repeat="sale in sales" >
{{sale.name}} {{ **AGE** }}
</li>
And,
If I have full date like '10-01-1989', then how can I?
If only year means,
view.PHP
<li ng-repeat="sale in sales" >
{{sale.name}} {{ yearToAge(sale.year) }}
</li>
.Js File:
$scope.yearToAge= function(y) {
return new Date().getFullYear() - y;
}
If Date format given,
view.PHP
<li ng-repeat="sale in sales" >
{{sale.name}} {{ dateToAge(sale.dob) }} // dob should be in dd/mm/yyyy format
</li>
.Js File:
$scope.dateToAge = function(date1){
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var today = curr_date + "-" + curr_month + "-" + curr_year;
var x = date1.split("-");
var y = today.split("-");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
var fdays = sdays - bdays;
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
return fyear;
}
Add this to your JS
$scope.ageFromYear = function(year) {
return new Date().getFullYear() - year;
}
Then, you can do this in your HTML:
<li ng-repeat="sale in sales" >
{{sale.name}} {{ ageFromYear(sale.year) }}
</li>
In PHP, the idea is built on converting the date into UNIX timestamp, then converting the current date too. then subtracting them, and finally dividing that number on the number of seconds in the year and get its floor to get the numbers of years.
This is a handled as following:
$d = '10-01-1989';
$dT = strtotime($d);
$cur = strtotime(date("m-d-Y"));
$diff = $cur - $dT;
$years = floor($diff/(60*60*24*365));
echo $years;
Checkout this DEMO: http://codepad.org/ErV8RauU

Resources