I have a JSON REST service that returns a list of periods with start dates. How can I convert the start date to javascript date?
[ {
"periodId": 1234,
"startDate": [ 2011, 12, 24]
},
{
"periodId": 5678,
"startDate": [ 2012, 12, 24]
}
]
I'm using ngResource in my service definition:
angular.module('periodservice',['ngResource']).
factory('Periods', function($resource) {
return $resource('../rest/periods', {}, {
query : {method : 'GET', params : {}, isArray : true}
});
});
The controller is pretty straight forward.
function EksternVareRedigeringCtrl ($scope, Periods){
$scope.periods = Periods.query(function(success, status, headers){
$scope.msgf = success;
console.log("this is the succsess);
}, function(errors){
$scope.msgf = errors;
console.log("This is an error....." + ' ' + $scope.msgf.status);
});
}
Now I display the date like this instead of converting it to a proper date:
<div class="period">Period: {{period[0]}}-{{period[1]}}-{{period[2]}}</div>
Convert to Javascript Date:
new Date(period.startDate[0], period.startDate[1]-1, period.startDate[2])
Note that I've used period.startDate[1]-1 because the months start at 0 (January) and end at 11 (December).
To process the dates only once, add the following snippet to your success callback:
angular.forEach($scope.periods, function (period) {
period.startDate = new Date(period.startDate[0], period.startDate[1]-1, period.startDate[2]);
});
Thanks a lot. It works perfectly!
Note. You do not have to subtract -1 from month number when supplying an array to new Date():
new Date([2012, 12, 24]) === new Date(2012, 11, 24);
Related
Hello all i am designing a leave management website with angularjs and ui-calendar.If a user takes a leave ,the values are taken from the database and displayed as an event in the calendar.Now what i want to do is ,if the user is not absent on particular day,it should be displayed as present event.Hope the following image helps understanding better.
Now vikki is taking leave on friday.I want to mark other dates as an event displaying in different color saying he s present.I need this to be in the week view.Please let me know if there is any way to do this thing.Following is my code
app.factory('calendarSer', ['$http','$rootScope', 'uiCalendarConfig', function ($http,$rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 450,
editable: true,
selectable: true,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startAt = start.toDate();
obj.startAt = new Date(obj.startAt).toUTCString();
obj.startAt = obj.startAt.split(' ').slice(0, 4).join(' ');
obj.endAt = end.toDate();
obj.endAt = new Date(obj.endAt).toUTCString();
obj.endAt = obj.endAt.split(' ').slice(0, 4).join(' ');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
calendar.fullCalendar('unselect');
},
eventRender: $scope.eventRender
}
};
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get("rest/leave/list", {
cache: true,
params: {}
}).then(function(data) {
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
$scope.events.push({
title: value.title,
description: value.description,
start: value.startAt,
end: value.endAt,
allDay: value.isFull,
stick: true
});
});
});
}
}
}]);
Thanking you
You need to also create the events array which would display the user is present. However, if you try to create the array in the front-end, then you would not know the other user information to fill the calendar.
"rest/leave/list" : will return that vikki is on leave, however what if the other user that has not taken any leave and is not returned in this array? how will you be able to fill the calendar saying user is present all the other days?
$scope.events.push({
title: value.title,
description: value.description,
start: value.startAt,
end: value.endAt,
allDay: value.isFull,
stick: true
});
$scope.eventSources = [$scope.events];
You are filling the events and binding it to the eventSources.
So you need to return something like below from the reponse "rest/leave/list":
{
title: "vikki",
description: "description",
startAt: "2017-05-05 00:00",
endAt: "2017-05-05 23:59",
isFull: true,
leave: true <- This will say he is absent
},
{
title: "vikki",
description: "description",
//The start and end date time will control the block that will be booked in the calendar
startAt: "2017-06-05 00:00",
endAt: "2017-01-06 23:59",
isFull: true,
leave: false <- This will say he is present
//This array will book the calendar from May-06 to end of the month.
//If you want the past, then create one in the past and send it from
//server
}
In the above array, you need to create separate rows for absent and present. For example , 1st row consist of January month where the user has not taken any leaves, so you create a row with Start date Jan 01 and End date Jan 30, In Feb, the user has taken one leave on say 5th. So you create three rows, row 1 with Feb 01 to Feb 04 as present, row 2 with Feb 05 as absent, and row 3 with Feb 06 - Feb 31 as present
Using the variable "leave" from the array, in the frontend you can change the colour. You can refer it from this how to achieve it.
Jquery Full calendar and dynamic event colors
I've been stuck on something simple for a little bit. I have the following response JSON:
{
"terminalName": "Montreal",
"shipThruLocationCodes":[
{
"shipThruLocationId": 112,
"shipThruLocationCode": "B84"
}
]
}
I have a select where I need to display terminalName (shipThruLocationCode) for each item in the shipThruLocationCodes array, there will only be one terminalName. The data is stored in an array in the controller called $scope.shipThrus. This is what I tried in my ng-repeat but it did not work:
data-ng-options="shipThru.terminalName for shipThru in shipThrus, item.shipThruLocationCode for item in shipThru.shipThruLocationCodes"
I think my idea is correct, but the comma (since I'm trying to display two values) is throwing an error.
So to summarize, the select should show the following for each item
"terminal Name" (shipThruLocationCode)
There will be only one terminal name and can be multiple location codes in the shipThrulocationCodes array.
Use a function to generate the options. Here's a Plunker to show you an example:
https://plnkr.co/edit/hxlowXWCS6BWh6gGfMMl?p=preview
HTML:
<select ng-model="main.selectedOption" ng-options="option.name for option in main.options"></select>
JS:
var app = angular.module('angularApp', []);
app.controller('MainCtrl', function($scope, $http) {
var vm = this;
vm.terminals = [
{
"terminalName": "Montreal",
"shipThruLocationCodes":[
{
"shipThruLocationId": 112,
"shipThruLocationCode": "B84"
}
]
},
{
"terminalName": "Somewhere else",
"shipThruLocationCodes":[
{
"shipThruLocationId": 113,
"shipThruLocationCode": "B9999"
}
]
}
];
vm.options = [];
generateOptions();
function generateOptions() {
for(var i = 0; i < vm.terminals.length; i++) {
var selectOption = {
name: vm.terminals[i].terminalName + " (" + vm.terminals[i].shipThruLocationCodes[0].shipThruLocationCode + ")"
};
vm.options.push(selectOption);
}
}
});
Check Plunker http://plnkr.co/edit/Vs2mC9zt3HmO9KGMzV6D?p=preview
If you have the list as:
$scope.shipThrus = [{
terminalName: "Montreal",
shipThruLocationCodes: [{
shipThruLocationId: 112,
shipThruLocationCode: "B84"
}, {
shipThruLocationId: 112,
shipThruLocationCode: "B89"
}]
}];
Just create this function:
function getLocationCodes(shipThru) {
return shipThru.shipThruLocationCodes.map(function(locationCode) {
return locationCode.shipThruLocationCode;
}).join(', ');
};
Which will parse the locationCodes to B84, B89.
Then parse the shipThrus:
$scope.shipThrus.forEach(function(shipThru) {
shipThru.label = shipThru.terminalName + ' (' + getLocationCodes(shipThru) + ')';
});
Now you can create the select element with the ng-options attribute as:
ng-options="shipThru.shipThruLocationCodes as shipThru.label for shipThru in shipThrus"
I am using angular bootstrap datepicker in my code. Problem with my requirement is that I want to have certain dates to be selected in the datepicker on which deliveries will be made. I am new to angular JS and have no Idea how to do that. Can someone help me in this ?
PS:I do not require the calendar to take input It is just needed to show the selected dates.
You can use the custom-class attribute to do this.
From the documentation
custom-class (date, mode) (Default: null) : An optional expression to
add classes based on passing date and current mode (day|month|year).
Here is a sample of the relevant handler adapted from the Angular UI Bootstrap example
...
$scope.events =
[
{
date: new Date(2015, 9, 1),
status: 'delivered'
},
{
date: new Date(2015, 9, 5),
status: 'delivered'
},
{
date: new Date(2015, 9, 15),
status: 'delivered'
}
];
$scope.getDayClass = function(date, mode) {
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i=0;i<$scope.events.length;i++){
var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
};
...
Plunker - http://plnkr.co/edit/vJl8hDUfsBOJsLXFNKWQ?p=preview
I am trying to access the obj from the select in my controller but the only thing that I end up getting is null and undefined.
<select
ng-change="watchActions(part)"
ng-options="part.serial as part.description for part in rawBaList.items"
ng-model="currentChose"
></select>
$scope.currentChose = null;
$scope.watchActions = function (obj) {
console.log($scope.currentChose);
console.log(obj);
};
$scope.$watch('currentChose', function (newValue, oldValue) {
if(newValue){
console.log("here the new value goes");
}
});
Here is the ex of data:
{
count: 2,
items: [
{serial: 2, description: 'here is some description'},
{serial: 24, description: 'some other description'}
]
}
it was a scope issue, $parent.currentChose fixed it
I have a link to an API which lists movies, each movie has title,id etc...
API: http://private-5d90c-kevinhiller.apiary-mock.com/angular_challenge/horror_movies
It also has an offers array inside which contains a 'provider_id' property.
I need to show how many movies are available at which provider.
But I dont know how, the best I came up with was:
{{movie.offers[0].provider_id}}
But that only shows the first provider on each movie.
What I want is to extract how many movies each provider has.
My Html:
<div ng-controller="ProviderController as provider">
<div ng-repeat="movie in provider.movies">
{{movie.offers[0].provider_id}}
</div>
</div>
My Main.js:
app.controller('ProviderController', function($http) {
var provider = this;
provider.movies = [];
$http({
url: 'some/path/horror_movies',
method: "GET",
}).success(function(data) {
provider.movies = data;
});
});
Also this is the structire of the json file:
[{
"id": 140524,
"title": "Dracula Untold",
"offers": [{
"provider_id": 2,
"retail_price": 14.99,
//...
}, {
"provider_id": 2,
"retail_price": 14.99,
}, {
"provider_id": 7,
"retail_price": 14.99,
}, ]
},
{
"id": 138993,
"title": "The Purge: Anarchy",
"offers": [
// ...
]
},
]
Any ideas ? Thanks.
You will need to change the structure of your database to have providers at the top level. A function achieving something like this should iterate over every movies offers, something like this:
function getProviders (movies) {
var providers = [],
movie = {},
offer = {};
for (var i = 0, max = movies.length; i < max; i += 1) {
movie = movies[i];
for (var j = 0; j < movies[i].offers.length; j += 1) {
offer = movie.offers[j];
if (typeof providers[offer.provider_id] === 'undefined') {
providers[offer.provider_id] = { movies: [] };
}
providers[offer.provider_id].movies.push(movie);
}
}
return providers;
}
I started a fiddle here: http://jsfiddle.net/d29tu8fg/1/
Before adding a movie to a provider, you might also want to check, if that movie already exists. You only need to do that though, if – like in your data – a movie can have two different offers from the same provider.
Add the providers to the $scope and in your view show the length:
<div ng-repeat="provider in providers track by $index">
{{provider.movies.length}}
</div>