Calculate age from given year in AngularJS - 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

Related

Diffrence between two datetime in desire format using angular js

How to check diffrence between two datetime in desire format using angular js.
var ms = moment($scope.date1,"yyyy-MM-dd HH:mm:ss").diff(moment($scope.date2,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Date diff.........",s);
output:
date1........ 2017-12-26 16:20:00
date2........ 2017-12-26 15:10:38
Diff- 01:10
(If should ignore date because there is not date diffrence and if date diffrence is there then it show display like 03:10:05)
Diff (In format- DD-HH-MM)
DD-Days
HH-Hours
MM-Minutes
Tried Code:
$scope.cdate = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
console.log("current time........",$scope.cdate);
$scope.Mydata=Data.timestamp; //I am Getting this data from response
this.getDateDiff = function(cdate, Mydata) {
let d1 = new Date($scope.cdate);
let d2 = new Date($scope.Mydata);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.cdate, $scope.Mydata);
console.log("days diff.........",$scope.dateDiff);
Output:
Input:
current time- 2017-12-29 10:19:41
Mydata- 2017-02-09 18:16:38
result is coming wrong-
{days: "23", hours: "16", minutes: "03", seconds: "03"}
You can achieve it by using native JavaScript.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38"
this.getDateDiff = function(date1, date2) {
let d1 = new Date(date1);
let d2 = new Date(date2);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.date1, $scope.date2);
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
</head>
<body ng-controller="MainCtrl">
<div>date1...... {{date1}}</div>
<div>date2...... {{date2}}</div>
<div>
<span>Diff - </span>
<span ng-if="dateDiff.days > 0">{{dateDiff.days}} : </span>
<span>{{ dateDiff.hours }} : </span>
<span>{{ dateDiff.minutes }}</span>
</div>
</body>
</html>
See if this works for you.
your controller file-
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38";
var diff = moment.utc(date1, "yyyy-MM-DD HH:mm:ss").diff(moment.utc(date2, "yyyy-MM-DD HH:mm:ss"), 'minutes');
var days=diff/(24*60);
var hours=diff/60;
var minutes=diff%60;
$scope.arr = [];
if(parseInt(days)){
arr.push(parseInt(days));
}
if(parseInt(hours)){
arr.push(('0'+hours).substring(-1, 2));
}
if(minutes){
arr.push(('0'+minutes).substring(-1, 2));
}
console.log(arr.join(':'));
Your html file-
...
<div>{{arr.join(':')}}</div>
...

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 ?

Calendar start weeks at Monday

What do you have to change so that week start from Monday not Sunday?
I can not post the code here, always get an error message and I do not understand because my English is not so good.
`function calendar() {
// show info on init
showInfo();
// vars
var day_of_week = new Array(
'So','Mo', 'Di',
'Mi', 'Do', 'Fr', 'Sa'),
month_of_year = new Array(
'Januar', 'Februar', 'März',
'April', 'May', 'Juni', 'July',
'August', 'September', 'Oktober',
'November', 'Dezember'),
Calendar = new Date(),
year = Calendar.getYear(),
month = Calendar.getMonth(),
today = Calendar.getDate(),
weekday = Calendar.getDay(),
html = '';
// start in 1 and this month
Calendar.setDate(1);
Calendar.setMonth(month);
// template calendar
html = '<table>';
// head
html += '<thead>';
html += '<tr class="head_cal"><th colspan="7">' + month_of_year[month] +
'</th></tr>';
html += '<tr class="subhead_cal"><th colspan="7">' + Calendar.getFullYear()
+
'</th></tr>';
html += '<tr class="week_cal">';
for (index = 0; index < 7; index++) {
if (weekday == index ) {
html += '<th class="week_event">' + day_of_week[index] + '</th>';
} else {
html += '<th>' + day_of_week[index] + '</th>';
}
}
html += '</tr>';
html += '</thead>';
// body
html += '<tbody class="days_cal">';
html += '</tr>';
// white zone
for (index = 0; index < Calendar.getDay(); index++) {
html += '<td class="white_cal"> </td>';
}
for (index = 0; index < 31; index++) {
if (Calendar.getDate() > index) {
week_day = Calendar.getDay();
if (week_day === 0) {
html += '</tr>';
}
if (week_day !== 7) {
// this day
var day = Calendar.getDate();
var info = (Calendar.getMonth() + 1) + '/' + day + '/' +
Calendar.getFullYear();
if (today === Calendar.getDate()) {
html += '<td><a class="today_cal" href="#" data-id="' +
info + '" onclick="return showInfo(\'' +
info + '\')">' +
day + '</a></td>';
showInfo(info);
} else {
html += '<td><a href="#" data-id="' +
info + '" onclick="return showInfo(\'' +
info + '\')">' +
day + '</a></td>';
}
}
if (week_day == 7) {
html += '</tr>';
}
}
Calendar.setDate(Calendar.getDate() + 1);
} // end for loop
return html;
}`
Codepen
In your day_of_week array change the order of days so that Sunday comes last.
Instead of this:
var day_of_week = new Array('So', 'Mo', 'Di','Mi', 'Do', 'Fr', 'Sa')
Do this:
var day_of_week = new Array('Mo', 'Di','Mi', 'Do', 'Fr', 'Sa', 'So')
Also, you should have a quick read of the help to see how to create links to external sites like Codepen etc (use the question mark '?' in the question editor if you need it). That will help you with things like posting code, links, formatting etc.
Also, when you are linking to an external code site (like Codepen or JSFiddle) you have to include some code in your question or answer as well as the link to the full code.
Update
OK - I see what you mean. Your day of week date does not correctly correspond to the day (as in Jun 3 2017 is a Saturday but showing as a Sunday) after my suggestion.
Because the order of the days changed (ie Monday became the first day of the week), you need to offset your weekday by -1 day.
In your white zone you need to change the first Calendar.getDay() loop from:
for (index = 0; index < Calendar.getDay(); index++)
to:
for (index = 0; index < Calendar.getDay() -1; index++)
That takes care of the first week in the month where there is white-space before the month. Then you need to fix all the other calendar dates. So change the next loop's Calendar.getDay() to offset that too. From this:
week_day = Calendar.getDay();
to this:
week_day = Calendar.getDay() -1;
You should go through the rest of your code and check other months to make sure you are not going to get an invalid date (NaN) because you are decreasing the date by one day.
Update 2
Try this piece of code. This provides a Monday - Sunday calendar and will create the table accordingly. You can easily modify the relevant table cells to include your hook into events and the actual date with styling etc.
If you wanted to you could create the table header with a loop for the days and with a little modification could make the first day of any given week whatever you wanted. I have tested it with each month of this year from Jan through June and the dates work fine.
_('#calendar').innerHTML = calendar();
// short querySelector
function _(s) {
return document.querySelector(s);
}
function calendar() {
var html = '<table><thead><tr>';
html += '<td>Mon</td>';
html += '<td>Tue</td>';
html += '<td>Wed</td>';
html += '<td>Thu</td>';
html += '<td>Fri</td>';
html += '<td>Sat</td>';
html += '<td>Sun</td>';
html += '</tr></thead>';
return html + '<tbody>' + calendarRows(new Date("2017/07/02")) + '</tbody></table>';
}
function calendarRows(dt) {
var html = '';
// Get the number of days in the month
var d = new Date(dt.getFullYear(), dt.getMonth()+1, 0);
var totalDays = d.getDate();
// Get the first day of the month
var f = new Date(dt);
f.setDate(1);
// The first day of the month for the date passed
var firstDayOfMonth = f.getDay();
// The actual date of the month in the calendar
var calendarDate = 1;
// The actual day in any given week. 1 === first day, 7 === last
var dayOfWeek = 1;
while (dayOfWeek < 9 && calendarDate <= totalDays) {
if (dayOfWeek === 8) {
dayOfWeek = 1;
}
// If we are at the start of a new week, create a new row
if (dayOfWeek === 1) {
html += '<tr>';
}
// Process the calendar day
html += '<td>';
// Is this the first day of the month?
if (calendarDate === 1 && firstDayOfMonth === dayOfWeek) {
html += calendarDate;
calendarDate ++;
}
else {
if (calendarDate === 1 || calendarDate > totalDays) {
html += ' ';
}
else {
html += calendarDate;
calendarDate ++;
}
}
html +='</td>';
// Are we at the end of a week?
if (dayOfWeek === 7) {
html += '</tr>';
}
dayOfWeek ++;
}
return html;
}
Hopefully that will work for you. You could always tighten up the code, but I leave that up to you. I've tried to make it easy to modify, but admit I put it together rather quickly to try and help you out.
And if you end up modifying the while loop variables just make sure you don't get yourself into an infinite loop.
Update 3
OK - I have created a Codepen for you that has it working with your formatting. You will still need to make the popup events work and add the relevant code to show events in the calendar. You can also tighten the code up if you need. I left it verbose so you can see what is going on.
_('#calendar').innerHTML = calendar();
// short querySelector
function _(s) {
return document.querySelector(s);
}
// show info
function showInfo(event) {
// Your code in here
}
// toggle event show or hide
function hideEvent(){
_('#calendar_data').classList.toggle('show_data');
}
function calendar() {
//showInfo();
var calDate = new Date("2017/06/02");
var weekdays = new Array( 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So');
var months = new Array(
'Januar', 'Februar', 'März',
'April', 'May', 'Juni', 'July',
'August', 'September', 'Oktober',
'November', 'Dezember');
// Working vars
var d = calDate.getDate(),
m = calDate.getMonth(),
y = calDate.getFullYear(),
day = calDate.getDay(),
today = calDate.getDate();
var html = '<table><thead>';
// Month
html += '<tr class="head_cal"><th colspan="7">' + months[m] + '</th></tr>';
// Year
html += '<tr class="subhead_cal"><th colspan="7">' + y + '</th></tr>';
// Days of week
html += '<tr class="week_cal">';
for (i = 0; i < 7; i++) {
if (today == i) {
html += '<th class="week_event">' + weekdays[i] + '</th>';
} else {
html += '<th>' + weekdays[i] + '</th>';
}
}
html += '</tr>';
html += '</thead>';
// Individual calendar days
html += '<tbody class="days_cal">' + calendarRows(calDate, d, m, y, day, today) + '</tbody></table>';
return html;
}
function calendarRows(calDate, d, m, y, day, today) {
var html = '';
// Get the number of days in the month
var tempDt = new Date(calDate.getFullYear(), calDate.getMonth()+1, 0);
var totalDays = tempDt.getDate();
// Get the first day of the month
tempDt.setDate(1);
var firstDayOfMonth = tempDt.getDay();
// Reset the day to 1 (first day of any month)
d = 1;
// Counter for tracking day of week. 1 === first day, 7 === last
var dayOfWeek = 1;
while (dayOfWeek < 9 && d <= totalDays) {
if (dayOfWeek === 8) {
dayOfWeek = 1;
}
// If we are at the start of a new week, create a new row
if (dayOfWeek === 1) {
html += '<tr>';
}
// Is this the first day of the month?
if (d === 1 && firstDayOfMonth === dayOfWeek) {
html += makeCell(d, m, y, today);
d ++;
}
else {
if (d === 1 || d > totalDays) {
html += '<td> </td>';
}
else {
html += makeCell(d, m, y, today);
d ++;
}
}
// Are we at the end of a week?
if (dayOfWeek === 7) {
html += '</tr>';
}
dayOfWeek ++;
}
return html;
}
function makeCell(d, m, y, today) {
var info = (m + 1) + "/" + d + "/" + y;
var cell = "<td><a href='#' ";
cell += d === today ? "class='today_cal' " : "";
cell += "data-id='" + info + "' onclick=\"return showInfo('" + info + "')\">";
cell += d + "</a></td>";
return cell;
}
If you modularize your code into smaller chunks (like the makeCell()), you will find it is easier to figure out what is going on and it is easier to get your brain around the more complex code problems.
Hope this helps.
Update 4
Updated the same Codepen - I think this fixed your issue, plus you can set the first day of the week to whatever day you want and the calendar should adjust accordingly. Code change was in the CalendarRows function:
function calendarRows(calDate, d, m, y, day, today) {
var html = '';
// Get the number of days in the month
var tempDt = new Date(calDate.getFullYear(), calDate.getMonth()+1, 0);
var totalDays = tempDt.getDate();
// Get the first day of the month
tempDt.setDate(1);
var firstDayOfMonth = tempDt.getDay();
// Reset the day to 1 (first day of any month)
d = 1;
// Weekdays are 0 === Sunday, 6 === Saturday
var firstDayOfWeek = 1, // <-- this means weeks start on Monday
lastDayOfWeek = 0, // <-- this measn Sunday
dayOfWeek = firstDayOfWeek,
safety = 0,
endLoop = false;
while (endLoop === false) {
safety ++;
if ((dayOfWeek === firstDayOfWeek && d > totalDays) || safety === 50) {
if (safety === 50) console.error("Infinite loop safety break");
break;
}
// If we are at the start of a new week, create a new row
if (dayOfWeek === firstDayOfWeek) {
html += '<tr>';
}
// Is this the first day of the month?
if (d === 1 && firstDayOfMonth === dayOfWeek) {
html += makeCell(d, m, y, today);
d ++;
}
else {
if (d === 1 || d > totalDays) {
html += '<td> </td>';
}
else {
html += makeCell(d, m, y, today);
d ++;
}
}
// Are we at the end of a week?
if (dayOfWeek === lastDayOfWeek) {
html += '</tr>';
}
// Add a day to the current day counter
dayOfWeek ++;
// If we get to Saturday, reset the next day to Sunday
if (dayOfWeek === 7)
dayOfWeek = 0;
}
return html;
}

Convert birthday to age in angularjs

I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.
i am displaying date like :
{{ friend.birthday }}
How can i display age instead of displaying birthday.
if it is possible to create filters than how to create filter and how to apply it.
You can implement a function:
Controller:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
HTML
{{ calculateAge(friend.birthday) }}
Or a filter:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
HTML
{{ friend.birthday | ageFilter }}
Age algorithm taken from this SO answer.
[EDIT] If the age is less than 1 year, and you want to show months, you can modify the ageFilter to calculate the month difference:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function monthDiff(d1, d2) {
if (d1 < d2){
var months = d2.getMonth() - d1.getMonth();
return months <= 0 ? 0 : months;
}
return 0;
}
return function(birthdate) {
var age = calculateAge(birthdate);
if (age == 0)
return monthDiff(birthdate, new Date()) + ' months';
return age;
};
});
Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year
If you're value is just for example "05/01/2016". This will be a useful code to convert the date to birthday.
AngularJS
app.filter('ageFilter', function(){
return function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
});
HTML
{{ relationTypePreDefined.birthdate | ageFilter }}
By the way I used this solution to convert a date coming from a jquery datepicker input to age.
If you are using momentjs. Then you can create filter simply by using this snippet
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
Idk why I can never reply to people, says I need more rep but to rep I need to comment.. whatever.
In response to #Dean Christian Armada's, I kept getting an error regarding the filter. But changing to the following seems to work fine so I do appreciate it!
$scope.getAge = function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
And for the HMTL
{{ getAge(birthdate) }}

ngClick not firing when $swipe is bound

I have an ngClick directive on elements that are also bound to $swipe. The ngClick doesn't fire (it was firing before the $swipe was added).
I'm using jQuery mobile combined with AngularJS.
Interestingly, my diagnostics show a swipe event with start and end the same - seems to contradict the minimum swipe distance, but perhaps the cancel function is being called. Possibly I could use the cancel function to find out where the click occurred but I feel I shouldn't have to do that.
The site is viewable at http://skimobile.cbdweb.net
HTML
<div id="matrix" data-role="page" ng-controller="matrixCtrl" ng-init="init()">
<div data-role="header">
<?php echo CHtml::encode($this->configs['SITENAME']); ?> Bookings
</div>
<div data-role="content">
<div class="lodgename noborder"> </div>
<div class="oneday onemonth" ng-repeat="m in months" ng-style="callMonthstyle(m)" ng-class="$last ? 'lastcol' : ''" on-finish-days>
{{monthNames[m.month]}} {{m.year}}
</div>
<br clear="both" />
<div class="lodgename noborder"> </div>
<div class="oneday" ng-style="callDaystyle()" ng-class="$last ? 'lastcol' : ''" ng-repeat="d in dates">
{{d.getDate()}}
</div>
<br clear="both" />
<div ng-repeat="lodge in data.lodges">
<div class="lodgename" ng-class="$last ? 'lastrow' : ''">{{lodge.lodgetitle}}</div>
<div class="oneday" ng-style="callDaystyle()" ng-class="($last ? 'lastcol' : '') + ' ' + ($parent.$last ? 'lastrow' : '')" ng-repeat="d in dates" ng-click="showDate(lodge, d)">
</div>
<br clear="both" />
</div>
<div ng-show="data.debug" style="margin-top: 20px;"
<ul>
<li>
move = {{swipe.move}}
</li>
<li>
start = {{swipe.start}}
</li>
<li>
end = {{swipe.end}}
</li>
<li>
scope.startDay = {{startDay}}
</li>
<li>
daysMoved = {{swipe.daysMoved}}
</li>
<li>
daysFinished = {{nDaysFinished}}
</li>
</ul>
</div>
<ul>
<?php foreach(Yii::app()->params['lodges'] as $lodgecode=>$lodge) {
echo "<li>" . $lodgecode . " = " . $lodge['lodgetitle'] . "</li>";
$lci = $this->lodgeconfigs[$lodgecode]['PREFIX_BOOKING_ID'];
echo "<LI>" . $lci . "</li>";
} ?>
</ul>
</div>
</div>
Javascript:
/* NG services */
var matrix = angular.module('Skimobile', ['ngTouch']);
matrix.factory('dayswidth', ['writeDays', function(){ // gets called on window change width
return function(scope, ww) {
var lodgename = $('.lodgename').first().width() + 4; // 4 = padding in lodgename class
var padding = 60 + lodgename;
var oldDisplayDays = scope.displayDays;
scope.displayDays = Math.min(28, (ww - padding)/scope.mindaywidth); // show at most 28 days, fewer if needed to maintain minimum width
scope.dayWidth = Math.floor( (ww-padding) / scope.displayDays );
if(oldDisplayDays!=scope.displayDays) { // avoid changing scope.dates as this will cause infinite recursion in the $digest on ng-repeat d in dates
scope.callWriteDays();
}
};
}]);
matrix.factory('writeDays', function() {
return function(scope) {
var d = new Date();
d.setTime(scope.startDay.getTime());
scope.dates = []; // repeat on this to draw days
scope.months = []; // repeat on this to draw months
var yearShown = false; // only show year once, when the month is long enough
var m = d.getMonth();
var daysLeft = 0; // days shown belonging to each month
for(i=0; i<scope.displayDays; i++) {
scope.dates.push(new Date(d.getTime()));
var oldd = new Date(d.getTime());
d.setDate(d.getDate()+1);
daysLeft++;
var newm = d.getMonth();
if(newm!=m) { // finished a month, display it
var newMonthObj = {month:m, days:daysLeft};
if(!yearShown && daysLeft*scope.dayWidth-1-4>3*scope.mindaywidth) {
newMonthObj.year = oldd.getFullYear();
yearShown = true;
} else {
newMonthObj.year = '';
}
scope.months.push(newMonthObj);
m = newm;
daysLeft = 0;
}
}
if(daysLeft>0) { // final month
newMonthObj = {month:m, days:daysLeft};
newMonthObj.year = yearShown ? '' : oldd.getFullYear();
scope.months.push(newMonthObj);
}
}
});
matrix.factory('daystyle', function(){
return function(scope) {
return {
'width': (scope.dayWidth-1) + 'px'
}; // -1 allows for border
}
});
matrix.factory('monthstyle', function(){
return function(scope, m) {
var days = m.days;
return {
'width': (scope.dayWidth*days-1-4) + 'px'
} // 1 for border, 4 for padding-left
}
});
matrix.directive('onFinishDays', function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attr) {
if(scope.$last === true) { // without this it gets called once per visible month!
$timeout(function() {
scope.$emit('daysFinished');
})
}
}
}
});
/* NG controllers */
function matrixCtrl($scope, dayswidth, writeDays, daystyle, monthstyle, $swipe) {
$scope.callDayswidth = function(w){
dayswidth($scope, w);
};
$scope.callDaystyle = function() {
return daystyle($scope);
}
$scope.callMonthstyle = function(m) {
return monthstyle($scope, m);
}
$scope.callWriteDays = function() {
return writeDays($scope);
}
$scope.data = _main; // passed via Yii layout file
$scope.mindaywidth = 30;
$scope.monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var d = new Date(); // initially the matrix starts from today
$scope.startDay = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
var w = $(window);
$scope.getWindowDimensions = function() {
return {'h': w.height(), 'w': w.width()};
};
$scope.$watch($scope.getWindowDimensions, function(newValue, oldValue){
$scope.callDayswidth(newValue.w);
}, true);
w.bind('resize', function() {
$scope.$apply();
})
$scope.showDate = function(lodge, d){
alert(lodge.lodgetitle + ' ' + d.getDate());
}
$scope.swipe = {};
$scope.nDaysFinished = 0;
$scope.$on('daysFinished', function(event) {
$scope.nDaysFinished++;
$swipe.bind($('.oneday'), {
end:function(loc){
$scope.swipe.end = loc.x;
$scope.swipe.daysMoved = Math.floor((loc.x - $scope.swipe.start) / $scope.dayWidth);
$scope.startDay.setTime($scope.startDay.getTime() - $scope.swipe.daysMoved*24*60*60*1000); // compute new start day at end of drag;
$scope.callWriteDays();
$scope.$apply();
}
})
});
}

Resources