I'm working on a small application that uses NASA's Open API. I currently have a controller for each request, depending on the rover the photos are being returned for. I'd like to combine these two controllers into one while being able to select the rover in which photos are returned.
app.controller('OpportunityController', function($scope, $http) {
// get date
let today = new Date();
let dd = today.getDate() - 5;
let mm = today.getMonth() + 1;
let yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = yyyy + '-' + mm + '-' + dd;
// set variables
$scope.baseUrl = "https://api.nasa.gov/mars-photos/api/v1/rovers/";
$scope.rover = ["Opportunity"];
$scope.date_params = "/photos?earth_date=" + today;
$scope.searchParams = $scope.rover + $scope.date_params;
$scope.key = "&api_key=API_KEY";
// request
$http.get($scope.baseUrl + $scope.searchParams + $scope.key)
.success(function(result) {
$scope.photos = result.photos;
console.log($scope.photos);
})
.error(function(error) {
console.log(error);
});
});
app.controller('MarsController', function($scope, $http) {
// get date
let today = new Date();
let dd = today.getDate()-1;
let mm = today.getMonth()+1;
let yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = yyyy+ '-' +mm+ '-' +dd;
// set variables
$scope.baseUrl = "https://api.nasa.gov/mars-photos/api/v1/rovers/";
$scope.rover = ["Curiosity"];
$scope.date_params = "/photos?earth_date=" + today;
$scope.searchParams = $scope.rover + $scope.date_params;
$scope.key = "&api_key=API_KEY";
// request
$http.get($scope.baseUrl + $scope.searchParams + $scope.key)
.success(function(result) {
$scope.photos = result.photos;
console.log($scope.photos);
})
.error(function(error){
console.log(error);
});
});
dont see a problem
$http.get($scope.baseUrl + $scope.searchParams + $scope.key)
.success(function(result) {
$scope.photos = result.photos;
console.log($scope.photos);
})
.error(function(error) {
console.log(error);
});
$http.get($scope.baseUrl + $scope.searchParams + $scope.key)
.success(function(result) {
$scope.photos = result.photos;
console.log($scope.photos);
})
.error(function(error) {
console.log(error);
});
Related
I thought it would be rather simple but I am struggle to successfully send response then modify my cloned response that is being stored in cache inside my service worker.
Ultimately I want to appended my cached data with the time and date of the fetch. I am using my service worker to first fetch this data from the network and if its not available fallback to the cache.
This is the code from my service worker
event.respondWith(
fetch(event.request)
.then(function(e) {
console.log('response', e)
var responseToCache = e.clone();
responseToCache.json().then(function(data) {
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
data.cached = { date: date, time: time }
return data
})
// var init = {
// status: response.status,
// statusText: response.statusText,
// headers: { 'X-Foo': 'My Custom Header' }
// };
// response.headers.forEach(function(v, k) {
// init.headers[k] = v;
// });
// var responseToCache = response.text().then(function(body) {
// var today = new Date();
// var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
// var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
// var bodyObj = JSON.parse(body)
// bodyObj.cached = { date: date, time: time }
// body = JSON.stringify(bodyObj)
// return new Response(body, init);
// });
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(requestURL, responseToCache);
});
return e
})
.catch(function() {
console.log('data offline')
return caches.match(requestURL);
})
);
Following code is returning $("#dob") and $("#anniversery") date as 2014-04-01T00:00:00
My code
<script>
$(function() {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#customerName").autocomplete({
source: function(request, response) {
$.ajax({
url: "ajaxCustomer",
dataType: "json",
data: {
str: $("#customerName").val(),
maxRows: 12
},
success: function(data) {
response($.map(data.customerList, function(item) {
console.log(item);
return {
label: item.customerName,
value: item.customerName,
id: item.customerId,
address: item.address,
dob: item.dob,
mobno: item.mobno,
annversery: item.anniversery
}
}));
},
error: function(data) {
alert(data.supplierList);
console.log(typeof data);
console.log(data);
alert('error');
}
});
},
minLength: 1,
select: function(event, ui) {
$("#customerId").val(ui.item.id);
$("#mobNo").val(ui.item.mobno);
$("#address").val(ui.item.address);
$("#dob").val(ui.item.dob);
$("#anniversery").val(ui.item.annversery);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
</script>
I want $("#dob") and $("#anniversery") its value in yyyy/mm/dd format
How to do this
I tried $("#dob").val(format_date(ui.item.dob));
function format_date(dt) {
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
document.write(dt);
document.write(year + '/' + month + '/' + day);
}
This is not working.
You have to cast the value you get from ui.item.dob to a Date.
var datefield = new Date(ui.item.dob);
$("#dob").val(format_date(datefield));
Then in your format_date function, remove the extra line at the bottom and put a return statement instead:
function format_date(dt) {
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
return dt;
}
You could use MomentJS
Apply format :
$("#anniversery").text(moment(ui.item.annversery).format('YYYY/MM/DD'));
var date = "2014-04-01T00:00:00";
var newDate = date.split("T")[0].replace(/-/g, "/");
console.log(newDate);
=> 2014/04/01
As already #display_name pointed you missed to parse the Date. Here a more simplified version of your code:
function format_date(dt) {
var dateString = new Date(dt); //parse the date
var formatedDate = dateString.getFullYear() + "/" +
('0'+ (dateString.getMonth() +1)).slice(-2) + "/" +
('0'+ dateString.getDate()).slice(-2);
return formatedDate; //return the formatted date to the input field
}
Now you can
$("#dob").val(format_date(ui.item.dob)); // incase if it is a textbox
try this..
var thisDate = "2013-01-01 00:00:00";
var thisDateT = thisDate.substr(0, 10);
You should create new Date object before using get functions:
var date = new Date(dt);
And then you can get the proper values:
var dd = date.getDate();
and so on.
Any suggestions on how to make my code cleaner and without code
duplication?As you can see there are a lot of repetitive declarations.
$scope.getStatistics = function(startDate, endDate) {
var start = startDate;
var date1 = start.getDate();
var month1 = (start.getMonth() +1);
var year1 = start.getFullYear();
var end = endDate;
var date2 = end.getDate();
var month2 = (end.getMonth() +1);
var year2 = end.getFullYear();
$http.get('/admin/api/stats?start=' + date1 + '-' + month1 + '-' + year1 + '&end=' + date2 + '-' + month2 + '-' + year2).success(function(data) {
$scope.stats = data;
});
}
$scope.getDiffPrev = function(startDate, endDate, computeDiff) {
var start = angular.copy(startDate)
start.setDate(start.getDate() - 7);
var date1 = start.getDate();
var month1 = start.getMonth() + 1;
var year1 = start.getFullYear();
var end = angular.copy(endDate)
end.setDate(end.getDate() - 7);
var date2 = end.getDate();
var month2 = end.getMonth() + 1;
var year2 = end.getFullYear();
$http.get('/admin/api/stats?start=' + date1 +'-'+ month1 +'-'+ year1 + '&end=' + date2 +'-'+ month2 +'-'+ year2 +'&computeDiff=true').success(function(data) {
$scope.stats = data;
});
}
function formatDate(date1){
var day1 = date1.getDate();
var month1 = (date1.getMonth() +1);
var year1 = date1.getFullYear();
return day1 + '-' + month1 + '-' + year1
}
$scope.getStatistics = function(startDate, endDate) {
$http.get('/admin/api/stats?start=' + formatDate(startDate) + '&end=' + formatDate(endDate)).success(function(data) {
$scope.stats = data;
});
}
$scope.getDiffPrev = function(startDate, endDate, computeDiff) {
var start = angular.copy(startDate)
start.setDate(start.getDate() - 7);
var end = angular.copy(endDate)
end.setDate(end.getDate() - 7);
$http.get('/admin/api/stats?start=' + formatDate(start) + '&end=' + formatDate(end) +'&computeDiff=true').success(function(data) {
$scope.stats = data;
});
}
You can created singleton service to avoid the code duplication, using this object you can access else where in your application.
For example you can use as foloows, I don't know exact code, but it will help you`.
angular.module('dateService', [ngResource])
.factory('DateService',['$http', function($http) {
var start, date1, month1, year1, end, date2, month2, result;
return {
date = function(startDate, endDate) {
start = startDate;
date1 = start.getDate();
month1 = (start.getMonth() +1);
year1 = start.getFullYear();
end = endDate;
date2 = end.getDate();
month2 = (end.getMonth() +1);
year2 = end.getFullYear();
$http.get('/admin/api/stats?start=' + date1 + '-' + month1 + '-' + year1 + '&end=' + date2 + '-' + month2 + '-' + year2).success(function(data) {
result = data;
});
return result;
}
}
}]);
angular.module('module-name', [dateService])
.cotroller('controller_name', ['DateService', function(dateService) {
$scope.getStatistics = function(startDate, endDate) {
var result = DateService.date(startDate, endDate);
result.then(function(data) {
$scope.start = data;
});
};
$scope.getDiffPrev = function(startDate, endDate, computeDiff) {
var result = DateService.date(startDate, endDate);
result.then(function(data) {
$scope.start = data;
});
};
}]);
I want to list all dates between 2 dates like..
list_dates('06/27/2013','07/31/2013');
This function will return all dates between 06/27/2013 - 07/31/2013 in array like..
['06/27/2013','06/28/2013','06/29/2013','06/30/2013','07/01/2013','...so_on..','07/31/2013'];
This function will work in all cases , Like older to newer , newer to older , or same dates like..
list_dates('06/27/2013','07/31/2013');
list_dates('07/31/2013','06/27/2013');
list_dates('07/31/2013','07/31/2013');
I do like...
function list_dates(a,b) {
var list = [];
var a_date = new Date(a);
var b_date = new Date(b);
if (a_date > b_date) {
} else if (a_date < b_date) {
} else {
list.push(a);
}
return list;
}
Demo : http://jsfiddle.net/fSGQ6/
But how to get dates between 2 dates ?
try this
list_dates('11/27/2013', '12/31/2013');
list_dates('03/21/2013', '02/14/2013');
list_dates('07/31/2013', '07/31/2013');
function list_dates(a, b) {
var list = [];
var a_date = new Date(a);
var b_date = new Date(b);
if (a_date > b_date) {
while (a_date >= b_date) {
var date_format = ('0' + (b_date.getMonth() + 1)).slice(-2) + '/' + ('0' + b_date.getDate()).slice(-2) + '/' + b_date.getFullYear();
list.push(date_format);
b_date = new Date(b_date.setDate(b_date.getDate() + 1));
}
} else if (a_date < b_date) {
while (b_date >= a_date) {
var date_format = ('0' + (a_date.getMonth() + 1)).slice(-2) + '/' + ('0' + a_date.getDate()).slice(-2) + '/' + a_date.getFullYear();
list.push(date_format);
a_date = new Date(a_date.setDate(a_date.getDate() + 1));
}
} else {
list.push(a);
}
console.log(list);
}
UPDATE: as poster requirement
var start = new Date(2013,06,27);
var end = new Date(2013,07,31);
var result =[];
var loop = true;
while(loop){
console.log(start.toISOString);
result.push(start);
start.setDate(start.getDate()+1)
if(start>end){
loop = false;
}
}
Date.prototype.getShortDate = function () {
// Do formatting of string here
return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
}
function list_dates(a, b) {
var a_date = new Date(a),
b_date = new Date(b),
list = [a_date.getShortDate()],
change = (a_date > b_date ? -1 : 1);
while (a_date.getTime() != b_date.getTime()) {
a_date.setDate(a_date.getDate() + change);
list.push(a_date.getShortDate());
}
return list;
}
I have a datepicker that highlights a selected week. It is using an ajax request. Which is where I am having a problem. When I select a week i.e. 29/08/11 and the page refreshes the highlighted week is no longer highlighted.
Datepicker.js
$(function()
{
var startDate;
var endDate;
var selectCurrentWeek = function()
{
window.setTimeout(function () { $('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')}, 1000);
}
function check(d) {
if(d.length() == 2) {
dd = d;
return dd;
} else {
dd = "0" + myDateParts[0];
return dd;
}
}
var selectedWeek;//remember which week the user selected here
$('.week-picker').datepicker( {
beforeShowDay: $.datepicker.noWeekends,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 1);
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = 'yy-mm-dd'
var newDate = $('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
var oldDate = document.getElementById('startDate');
var date_textnode = oldDate.firstChild;
var date_text = date_textnode.data;
myDateParts = date_text.split("-");
var dd = myDateParts[2];
var mm = myDateParts[1];
var yy = myDateParts[0];
selectCurrentWeek();
window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd; <<
At this point above this is where the window is refreshed and it GETs the URL. So that when I select a date it outputs like the following http://0.0.0.0:3000/timesheet?week_commencing=2011-09-05
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
index.html.erb
window.onload = function getURL(){
var url = document.location.href;
urlSplit = url.split("/timesheet");
if(urlSplit[1]== "")
{
var d = getMonday(new Date());
dd = zeroPad(d.getDate(),2);
mm = zeroPad(d.getMonth()+1,2);
yy = d.getFullYear();
document.getElementById('startDate').innerHTML = yy + "-" + mm + "-" + dd;
//window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd;
}
else
{
week = url.split("week_commencing=");
//return week[1];
document.getElementById('startDate').innerHTML = week[1];
}
}
Note
The window.onload URL function gets the week commencing from the url
Jsfiddle - Including datepicker
http://jsfiddle.net/YQ2Zw/12/
Update
You can use the defaultDate to set the initial date selected on the datepicker, and simulate a click event on the calendar to highlight the week:
var selectDate = '09/29/2011';
$('.week-picker').datepicker({
defaultDate: selectDate
}).click(function(event) {
// highlight the TR
$(".ui-datepicker-current-day").parent().addClass('highlight');
// highlight the TD > A
$(".ui-datepicker-current-day:eq(0)").siblings().find('a').addClass('white');
}).click();
Example: http://jsfiddle.net/william/YQ2Zw/15/
Update
Assuming Datepicker.js is loaded in timesheet, you should be able to do that with two more lines:
window.onload = function getURL(){
var url = document.location.href;
urlSplit = url.split("/timesheet");
if(urlSplit[1]== "")
{
var d = getMonday(new Date());
dd = zeroPad(d.getDate(),2);
mm = zeroPad(d.getMonth()+1,2);
yy = d.getFullYear();
document.getElementById('startDate').innerHTML = yy + "-" + mm + "-" + dd;
//window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd;
$('.week-picker').datepicker({
defaultDate: mm + '/' + dd + '/' + yy
}).click();
}
else
{
week = url.split("week_commencing=");
//return week[1];
document.getElementById('startDate').innerHTML = week[1];
}
}