I am trying to paginate a list of events (using ng-repeat) by week in AngularJS. I have a custom filter working that only displays the events within the current week, but I am trying to add functionality to look at future and past weeks.
Here is the filter I am using for the event lists -
$scope.week = function(item) {
var weekStart = moment().startOf('week');
var weekEnd = moment().endOf('week');
var eventTime = moment(item.jsdatetime);
if (eventTime >= weekStart && eventTime <= weekEnd) return true;
return false;
};
I have tried using ng-click to call a function that uses moment.js to .add(7, 'days'); to the weekStart and weekEnd variables but can't seem to get it to work.
Any help would be appreciated.
Here's a CodePen with the basic functionality going on - http://codepen.io/drewbietron/pen/xbKNdK
The moment() always return the current date/time.
You need to store a reference to it to a variable, and then use that for manipulations.
(and since you have other variables depending on it, i would create a function that sets all those variables at once)
So in the controller i changed the top part to
var currentDate,
weekStart,
weekEnd,
shortWeekFormat = 'MMMM Do';
function setCurrentDate(aMoment){
currentDate = aMoment,
weekStart = currentDate.clone().startOf('week'),
weekEnd = currentDate.clone().endOf('week')
}
// initialize with current date
setCurrentDate(moment());
// use these methods for displaying
$scope.currentWeek = function(){ return currentDate.format(shortWeekFormat); };
$scope.currentWeekStart = function(){ return weekStart.format(shortWeekFormat); };
$scope.currentWeekEnd = function(){ return weekEnd.format(shortWeekFormat); };
Then create two methods for going to next/previous week
$scope.nextWeek = function(){
setCurrentDate(currentDate.add(7,'days'));
};
$scope.prevWeek = function(){
setCurrentDate(currentDate.subtract(7,'days'));
};
(moment.js implements valueOf so you do direct comparisons)
And finally change your week filter to actually compare the dates (using .isSame(), .isBefore() and .isAfter()) instead of the moment objects (which was wrong as you cannot do direct comparisons on custom objects)
$scope.week = function(item) {
var eventTime = moment(item.jsdatetime);
if ((eventTime.isSame(weekStart) || eventTime.isAfter(weekStart))&&
(eventTime.isSame(weekEnd) || eventTime.isBefore(weekEnd))) return true;
return false;
};
$scope.week = function(item) {
var eventTime = moment(item.jsdatetime);
return (eventTime >= weekStart && eventTime <= weekEnd);
};
(you also, most likely, want the ng-repeat on the li elements and not the ul)
Demo at http://codepen.io/gpetrioli/pen/QwLRQB
The weekStart and weekEnd variables don't exist outside of the scope of week(item). If you're using ngClick to call a function that tries to modify those variables, it'll just return undefined. I don't know how your layout is but I would pull those two variables outside of the week function and make them $scope variables.
Additionally, I would have ngClick call a function that would change the two $scope variables (either adds 7 or subtracts 7 depending on which direction you want to go in).
$scope.weekStart = moment().startOf('week');
$scope.weekEnd = moment().endOf('week');
$scope.week = function(item) {
var eventTime = moment(item.jsdatetime);
if (eventTime >= $scope.weekStart && eventTime <= $scope.weekEnd) return true;
return false;
};
$scope.update= function(direction) {
$scope.weekStart.add(direction, 'days');
$scope.weekEnd.add(direction, 'days');
}
And create two buttons in your view:
Previous week
Next week
Related
I want to convert the commit date and time to time stamp which I get from my APIs.
But I don't know how to do this in angular?
Here is my controller code :
var commitDate = item.commitMetaData.commitDate;
var dat = new Date(commitDate);
But it says "Invalid Date"
PS: Thanks in advance
What you could do is generate the date from the values montValue , year, dayOfMonth
with plain Javascript you could just do
var d = new Date();
d.setMonth(commitDate.monthValue +1); //see explanation below
d.setDate(commitDate.dayOfMonth);
d.setYear(commitDate.year);
be careful the months start at 0 so January is actually 0 so in your example you would have to add +1
You can also create a filter for this
.filter('createDate', function ($filter) {
return function (input) {
if (input != null && input != undefined) {
var d = new Date();
d.setMonth(input.monthValue +1); //see explanation below
d.setDate(input.dayOfMonth);
d.setYear(input.year);
return d;
}
};
})
and call it like
var commitDate = item.commitMetaData.commitDate;
var dat = $filter('createDate')(commitDate);
reference JS Date
I am trying to modify a plugin, it is a calendar. When you press on the dates that are not part of the month (at the beginning and the end of the month) it changes to the next or previous month. I am trying to disable this, and I found what part of the code to change, but when I make the changes (or add a console.log message), nothing gets reflected when I execute ionic serve. One thing is, the calendar is written in AngularJS - while I am using Ionic, which uses Angular 2. The part of the code I am trying to change looks like this:
$scope.select = function (viewDate) {
console.log("in in in select &&&&&&&");
var selectedDate = viewDate.date,
events = viewDate.events,
views = scope.views,
dates,
r;
if (views) {
dates = views[scope.currentViewIndex].dates;
var currentCalendarDate = ctrl.currentCalendarDate;
var currentMonth = currentCalendarDate.getMonth();
var currentYear = currentCalendarDate.getFullYear();
var selectedMonth = selectedDate.getMonth();
var selectedYear = selectedDate.getFullYear();
var direction = 0;
if (currentYear === selectedYear) {
if (currentMonth !== selectedMonth) {
direction = currentMonth < selectedMonth ? 1 : -1;
}
} else {
direction = currentYear < selectedYear ? 1 : -1;
}
ctrl.currentCalendarDate = selectedDate;
if (direction === 0) {
if (ngModelCtrl) {
ngModelCtrl.$setViewValue(selectedDate);
}
var currentViewStartDate = ctrl.range.startTime,
oneDay = 86400000,
selectedDayDifference = Math.floor((selectedDate.getTime() - currentViewStartDate.getTime()) / oneDay);
for (r = 0; r < 42; r += 1) {
dates[r].selected = false;
}
if (selectedDayDifference >= 0 && selectedDayDifference < 42) {
dates[selectedDayDifference].selected = true;
scope.selectedDate = dates[selectedDayDifference];
}
} else {
console.log("is getting here &&^^%%$$");
//ctrl.moveOnSelected = true;
//ctrl.slideView(direction); <----- I AM COMMENTING THIS OUT TO STOP THE SLIDE!!!
}
...
At the bottom of the above code block, I made an arrow pointing to the two lines I am commenting out. I also added console.log statements, one at the beginning of the function, and one in the middle, and neither of them are output into the console (the above is the select function which happens when a date on the calendar is selected).
The code structure of the plugin is like this:
angular.module("ui.rCalendar.tpls", ["templates/rcalendar/calendar.html","templates/rcalendar/day.html","templates/rcalendar/displayEvent.html","templates/rcalendar/month.html","templates/rcalendar/monthviewDisplayEvent.html","templates/rcalendar/monthviewEventDetail.html","templates/rcalendar/week.html"]);
angular.module('ui.rCalendar', ['ui.rCalendar.tpls'])
.constant('calendarConfig', {
formatDay: 'dd',
formatDayHeader: 'EEE',
formatDayTitle: 'MMMM dd, yyyy',
formatWeekTitle: 'MMMM yyyy, Week w',
formatMonthTitle: 'MMMM yyyy',
formatWeekViewDayHeader: 'EEE d',
formatHourColumn: 'ha',
calendarMode: 'month',
showEventDetail: true,
startingDayMonth: 0,
startingDayWeek: 0,
allDayLabel: 'all day',
noEventsLabel: 'No Events',
eventSource: null,
queryMode: 'local',
step: 60,
autoSelect: true,
monthviewDisplayEventTemplateUrl: 'templates/rcalendar/monthviewDisplayEvent.html',
monthviewEventDetailTemplateUrl: 'templates/rcalendar/monthviewEventDetail.html',
weekviewAllDayEventTemplateUrl: 'templates/rcalendar/displayEvent.html',
weekviewNormalEventTemplateUrl: 'templates/rcalendar/displayEvent.html',
dayviewAllDayEventTemplateUrl: 'templates/rcalendar/displayEvent.html',
dayviewNormalEventTemplateUrl: 'templates/rcalendar/displayEvent.html'
})
.controller('ui.rCalendar.CalendarController'
...
.directive('monthview', ['dateFilter', function (dateFilter) {
THIS IS WHERE THE SELECT FUNCTION IS
...
This is an angularjs plugin in an Ionic app, remember it is built on Angular 2 not angularjs. Im not sure where the plugin javascript file gets loaded.
I was looking in the wrong package folder, I didn't realized I had installed a typescript version.
I got a wired error
I have directive date picker
I have watch listener while the date change
$scope.$watch('model', function (newDate) {
if (newDate) {
if ($scope.hideDay) {
$scope.dateFields.day = 1;
} else {
$scope.dateFields.day = new Date(newDate).getUTCDate();
}
$scope.dateFields.month = new Date(newDate).getUTCMonth() +1;
$scope.dateFields.year = new Date(newDate).getUTCFullYear();
} else {
if ($scope.hideDay) {
$scope.dateFields.day = 1;
} else {
$scope.dateFields.day = null;
}
$scope.dateFields.month = null;
$scope.dateFields.year = null;
}
});
My weird problem is that I have a search box
<input class="free-txt" ng-model="search.name" placeholder="Free search" />
When I typed in the search box The watch model changed with no reason.
What can be the reason for this bug and how can I fixed it?
Here is the full demo
https://embed.plnkr.co/yGqE33kZNwGz7NaNDOD5/
Select day
Select Month
Open the Year modal than Write in the free text "78"
Select The year
The bug when Typing in the free text the day and month change to null
by default angular $watch watch object by reference
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
objectEquality:
Compare for object equality using angular.equals instead of comparing for reference equality.
(default: false)
try to add a parametre to true for watching object or use watchcollection and give it the variables you need
$scope.$watch('model', function (newDate) {
...
},true );
the directive update the model only when the date is valid :
$scope.checkDate = function () {
$timeout(function () {
var date = rsmDateUtils.checkDate($scope.dateFields);
if (date) {
// the watch is called what date is valid with a year
if ($scope.hideDay) {
$scope.model = $filter('date')(date, 'yyyy-MM');
} else {
$scope.model = $filter('date')(date, 'yyyy-MM-dd');
}
}
});
};
I Want to filter event by date but date is pass by normal input type="text" not kendo default datepicker.And display passing date in kendo schduler header But cant not change view date.This is my code.........
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler.view().startDate(item.StartDate);
scheduler.view().endDate(item.EndDate);
scheduler.view(("day"));
$scope.scheduler.dataSource.read();
};
This is my filter param
parameterMap: function (options, operation) {
var popupheight = $(window).height() - 180 + 'px';
$scope.popupWraperForTryout = popupheight;
var scheduler = $("#scheduler").data("kendoScheduler");
if (searchCount != 0) {
if (operation === "read") {
return {
filterByPersonalEvent: $scope._filterParamObj.filterBypersonal,
filterBySignUpRequired: $scope._filterParamObj.filterBySingupRequired,
filterByPaidOrFree: $scope._filterParamObj.filterByPaid,
filterByEventStatus: $scope._filterParamObj.eventStatusId,
filterByEventType: $scope._filterParamObj.eventTypeId,
selectedTeam: $scope._filterParamObj.seasonTeamId,
filterByStartDate: scheduler.view().startDate(),
filterByEndDate: scheduler.view().endDate(),
OrgId: _orgId,
UserTimezone: global.userTimezoneOffset
}
}
}
},
I am so tired.This code is not change in view date.Please help me
Several issues here - the day view shows just one day; you can't set startDate and endDate - just date.
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
//scheduler.view().startDate(item.StartDate);
//scheduler.view().endDate(item.EndDate);
scheduler.view("day");
// item.StartDate should be Date object - like scheduler.date(new Date("2013/6/6"));
scheduler.date(item.StartDate);
$scope.scheduler.dataSource.read();
};
If you need to set some explicit date range to filter - you can do it, but still you can't show more than just one day in day view.
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler._myFilterStartDate = item.StartDate;
scheduler._myFilterEndDate = item.EndDate;
scheduler.view("day");
scheduler.date(item.StartDate);
$scope.scheduler.dataSource.read();
};
And in parameter map:
...
return {
filterByStartDate: scheduler.view().startDate(),
filterByEndDate: scheduler.view().endDate(),
myFilterStartDate: scheduler._myFilterStartDate,
myFilterEndDate: scheduler._myFilterEndDate,
OrgId: _orgId,
UserTimezone: global.userTimezoneOffset
};
...
I am trying to display the time difference between my {{trade.timer}} and the current time but coudn't succeed after many tries.
I am looking to make the $scope.gains[i].timer = vtime - "CURRENTTIME"
Here is my code:
$scope.updatetimerValue = function (timerValue){
$.each(timerValue, function(k, v) {
for (var i =0; i < $scope.gains.length ; i ++) {
if($scope.gains[i].orderid == v.orderid){
$scope.gains[i].timer = v.time;
}
}
});
}
<td>{{gain.timer | date: 'HH:mm'}}</td>
Any idea?
Note: v.time time format is yyyy-MM-dd HH:mm:ss
You can get date difference between two days with basic javascript.
var date = new Date('10/27/2014');
var currentDate = new Date();
var milisecondsDiff = date-currentDate;
var secondsDiff = miliseconds/1000;
var minutesDiff = seconds/60;
var hoursDiff = minutes/60;
var daysDiff = hours/24;
Also I suggest don't mix up AngularJS and JQuery.
And instead $.each use the angular.forEach
angular.forEach(values, function(value, key) {
///
});
or even better to use simple for loop, because it works faster.