Error displaying date using angularfire and firebase - angularjs

I am having trouble displaying a date (stored as Unix timestamp integer) from firebase using Angularfire.
I have the following html:
<div class="form-group"">
<label for="message-followUp" class="control-label">Follow Up Date:</label>
<input type="date" id="message-followUp" ng-model="postToUpdate.followUp">
</div>
and the following controller:
$scope.notePost = function (id) {
var firebaseObj = new Firebase("https://firebase_url/Records/" + id);
$scope.postToUpdate = $firebaseObject(firebaseObj);
};
Within the data returned I have a key called 'followUp' that contains the Unix timestamp. When displaying the html I get the following error:
Error: [ngModel:datefmt] Expected 1466773470397 to be a date
I was hoping I could wrap 'postToUpdate.followUp' in new date() but that doesn't work
How do I convert the Unix timestamp to the correct date format (yyyy-MM-dd) so it displays without getting the error?
Thanks

The data you are retrieving from firebase is a string and the inux timestamp should be an Integer when passed to new Date.
JS
$scope.notePost = function (id) {
var firebaseObj = new Firebase("https://firebase_url/Records/" + id);
$scope.postToUpdate = $firebaseObject(firebaseObj);
$scope.postToUpdate.$loaded(
function(data) {
console.log(data);
$scope.date = new Date(parseInt(data.followUp));
},
function(error) {
console.error("Error:", error);
}
);
};
HTML
<div class="form-group"">
<label for="message-followUp" class="control-label">Follow Up Date:</label>
<input type="date" id="message-followUp" ng-model="date">
</div>
Working jsFiddle here.

Related

Error: "[ngModel:datefmt] Expected `08:00:00` to be a date

I am working on mvc application using angularJs , i have an issue on html input type time i cannot get the time from database and bind it with input type time .
This is error message on debug angularjs
Error: "[ngModel:datefmt] Expected08:00:00to be a date
Error: "[ngModel:datefmt] Expected17:00:00to be a date
this is the html
<div class="form-group">
<label class="control-label"> Time From</label>
<input ng-model="Branch_TimeFrom" type="time" name="Branch_TimeFrom">
</div>
<div class="form-group">
<label class="control-label"> Time To</label>
<input ng-model="Branch_TimeTo" type="time" name="Branch_TimeTo">
</div>
APP.JS
//get single record by ID
$scope.getForUpdate = function (Branch) {
debugger
$scope.Branch_ID = Branch.Branch_ID;
$scope.Branch_Name = Branch.Branch_Name;
$scope.Branch_Address = Branch.Branch_Address;
$scope.Branch_email = Branch.Branch_email;
$scope.Branch_Notes = Branch.Branch_Notes;
$scope.Branch_TimeFrom = moment(Branch.Branch_TimeFrom).format('HH:mm:ss');
$scope.Branch_TimeTo = moment(Branch.Branch_TimeTo).format('HH:mm:ss');
$scope.Branch_Manager = Branch.Branch_Manager;
$scope.Branch_Phone = Branch.Branch_Phone;
$scope.saturday = Branch.saturday;
};
this is the result on debug code,my question is how to display time to input type time i tried alot of solutions but did't fix it so far .
any advice
i just changed my code to that solved my issue
$scope.getForUpdate = function (Branch) {
debugger
$scope.Branch_ID = Branch.Branch_ID;
$scope.Branch_Name = Branch.Branch_Name;
$scope.Branch_Address = Branch.Branch_Address;
$scope.Branch_email = Branch.Branch_email;
$scope.Branch_Notes = Branch.Branch_Notes;
$scope.Branch_TimeFrom = new Date(moment(Branch.Branch_TimeFrom));
$scope.Branch_TimeTo = new Date(moment(Branch.Branch_TimeTo));
$scope.Branch_Manager = Branch.Branch_Manager;
$scope.Branch_Phone = Branch.Branch_Phone;
$scope.saturday = Branch.saturday;
};
When using input type time in editable form, if the control shows seconds and millisecond to enter it becomes bit nasty. Also entering time in millisecond in a form by user seems bit odd, unless otherwise its a requirement.
We can write a common method to remove the second and millisecond part in the controller.
getFormatDate = function (val) { // assuming val is date like "/Date(946673340000)/"
if (val != undefined) {
date = new Date(val.match(/\d+/)[0] * 1); // creating a date object from val
return new Date(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes());
}
}

AngularJs Auto Complete Search

So this works with static data, but when I push data with a $http this autocomplete does not work. The data pushes to the empty array of airport_list but something is happening when I try to use airport_list in for the autocomplete. Not sure what is is. I can only find answers which pertain to static data.
This is updated per everyones help.
Here is the controller
app.controller('selectCtrl', function($scope, $http) {
$scope.airport_list = null;
$http({
url: 'someUrl.com',
method: 'GET'
})
.then((response) => {
angular.forEach(response.data.airports, function(value, key) {
$scope.airport_list = response.data.airports;
})
$scope.airports = $scope.airport_list;
});
$scope.selectAirport = function(string) {
$scope.airport = string;
$scope.hidelist = true;
};
})
Here is the template
<div class="control">
<div>
<input
type="text"
name="airport"
id="airport"
ng-model="airport"
ng-change="searchFor(airport)"
placeholder="From..."
/>
<div class="airport-container-dropdown" ng-hide="hidelist">
<div
class="airport-list"
ng-repeat="airport in airports"
ng-click="selectAirport(airport)"
>
{{ airport.name }}
</div>
</div>
</div>
</div>
I really would like to do this without using bootstrap typeahead.
Thank you for looking at this.
I have made changes as recommended by below answers and the $http request is feeding into the autocomplete as a whole list but searching by name does not work and clicking on name sets [object, object]
this would be the code which is specific to that functionality.
$scope.searchFor = function(string) {
$scope.hidelist = false;
const output = [];
angular.forEach($scope.airport_list, function(airport) {
if (airport[0].toLowerCase().indexOf(string.toLowerCase(airport)) >=
0) {
output.push(airport);
}
});
$scope.airports = output;
};
$scope.selectAirport = function(string) {
$scope.airport = string;
$scope.hidelist = true;
};
Try this:
$scope.airport_list = response.data.airports;
What I am seeing is that you have an array: $scope.airport_list = [];
When you make your http request, you push what I would understand to be an array of airports into that array. So you end up with your airport array from the backend at the first position of $scope.airport_list, vs. $scope.airport_list being the actual list.
For your search method, you should change the following:
In your HTML:
ng-change="searchFor(airport.name)"
In your JS:
I've renamed your function and changed the input variable to be more clear. You were passing in a full airport, but treating it as a string. You need to compare your provided airport name to that of the airports in the array. So you iterate over the array, and compare each element's name property to what you pass in.
$scope.searchFor = function(airportName) {
$scope.hidelist = false;
const output = [];
angular.forEach($scope.airport_list, function(airport) {
if (airport.name.toLowerCase() === airportName) {
output.push(airport);
}
});
$scope.airports = output;
console.log($scope.airports);
};
I have provided minimal changes to your code to implement this, however I suggest you look at this SO post to filter drop down data more appropriately.
Angularjs Filter data with dropdown
If you want to simply filter out what is displayed in the UI, you can try this in your HTML template. It will provide a text field where you supply a partial of the airport name. If at least one character is entered in that box, the list will display on the page, with the appropriate filtering applied. This will avoid having to call functions on change, having a separate array, etc.
<input type="text" name="airport" id="airport" ng-model="airportSearch.name" placeholder="From..." />
<div class="airport-container-dropdown" ng-hide="!airportSearch.name">
<div class="airport-list"
ng-repeat="airport in airport_list | filter:airportSearch"
ng-click="selectAirport(airport)">
{{ airport.name }}
</div>
</div>

Change date format for ui datepicker (jHipster)

I've generated a Spring Boot + Angular 1 based project in jHipster. I'm kind of newbie the Angular world. Everything works fine, but when I input the date using the provided UI datepicker (https://angular-ui.github.io/bootstrap), its format is yyyy-MM-dd, even if I've defined spanish to be my only language package (I would prefer it to be dd/MM/yyyy). That's the code snippet for the input:
regulation-version-dialog.html
<div class="form-group">
<label class="control-label"
data-translate="selfprotectionApp.regulationVersion.versionDate"
for="field_versionDate">Version Date</label>
<div class="input-group">
<input id="field_versionDate" type="text" class="form-control"
name="versionDate" uib-datepicker-popup="{{dateformat}}"
ng-model="vm.regulationVersion.versionDate"
is-open="vm.datePickerOpenStatus.versionDate" /> <span
class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="vm.openCalendar('versionDate')">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</div>
</div>
Here there's the {{dateformat}} binding, but I don't know where jHipster picks it from. The only matches are in the date-util.service.js file, but changing the format here doesn't seem to affect.
date-util.service.js
(function() {
'use strict';
angular
.module('selfprotectionApp')
.factory('DateUtils', DateUtils);
DateUtils.$inject = ['$filter'];
function DateUtils($filter) {
var service = {
convertDateTimeFromServer: convertDateTimeFromServer,
convertLocalDateFromServer: convertLocalDateFromServer,
convertLocalDateToServer: convertLocalDateToServer,
dateformat: dateformat
};
return service;
function convertDateTimeFromServer(date) {
if (date) {
return new Date(date);
} else {
return null;
}
}
function convertLocalDateFromServer(date) {
if (date) {
var dateString = date.split('-');
return new Date(dateString[0], dateString[1] - 1, dateString[2]);
}
return null;
}
function convertLocalDateToServer(date) {
if (date) {
return $filter('date')(date, 'yyyy-MM-dd');
} else {
return null;
}
}
function dateformat() {
return 'yyyy-MM-dd';
}
}
})();
Of course, I could replace the {{dateformat}} expression by some date format in HTML, but I would like to do it for the whole project.
There is no default way in angular JS to set up dateformat from a provider for example for the complete project.
What you could do; is define a filter with your format to be used like that : {{dateformat | date:'MM/dd/yyyy'}}
OR define a global filter for that requirement to make it more easy to type (source https://stackoverflow.com/a/18402623/3687474 )
.filter('myDate', function($filter) {
var angularDateFilter = $filter('date');
return function(theDate) {
return angularDateFilter(theDate, 'dd MMMM # HH:mm:ss');
}
});
and used it like that : {{dateformat | myDate }}
The ultimate solution is to used a very robust library to manage your dates such as moment.js and it angularjs diretives
this is my favorite solution; as it is more scalable for many uses and date manipulation.
However; adding libraries to your project has always a performance cost ;)

How to use readonly() method to Kendo UI datetime input created with AngualrJS

In this pagei found this example
<input id="datepicker" />
<script>
$("#datepicker").kendoDatePicker();
vardatepicker = $("#datepicker").data("kendoDatePicker");
datepicker.readonly();</script>
How can use this readonly function to datetime input created by Angular?
example of datetime with angular
I want to add disabled input using only AngularJs
At my code:
<input kendo-date-picker
id="linesDateObject"
k-options="linesPickDateOptions"
k-ng-model="linesDateObject"
style="width:200px;"
class="pull-left" />
In my controller
$scope.linesPickDateOptions = {
value: new Date(),
format: "dd/MM/yyyy",
change: function () {
var value = this.value();
console.log(value);
}
}
I want to add disable property inside $scope.linesPickDateOptions object
$('#datepicker').data('kendoDatePicker').enable(false);

Backbone.js create method not sending parameters to sinatra

I'm new to backbone and trying to set it up in Sinatra, but I can't seem to get a simple create working.
I've set up my model/collection as so:
var TEAM_ID = window.location.pathname.split('/')[1]; // From url
$(function () {
var TeamMember = Backbone.Model.extend({
defaults: {
name : ""
}
});
var TeamMembers = Backbone.Collection.extend({
model: TeamMember,
url: "/" + TEAM_ID + "/team-members.json"
});
var teamMembers = new TeamMembers;
var TeamMemberView = Backbone.View.extend({
events: {
"click #new-team-member-form .submit-button" : "handleNewTeamMember"
},
handleNewTeamMember: function(data) {
var inputField = $('input[name=new_team_member_name]');
console.log("Pre create");
// This doesn't get sent to the server!!
var teamMember = teamMembers.create({name: inputField.val());
console.log("Post create");
return false; // Don't submit form
},
render: function() {
console.log("Render team member");
return this;
}
});
// ...
var teamMemberView = new TeamMemberView({el: $('#week-view')});
});
The html looks like:
<table id="week-view">
<!-- ... -->
<form id="new-team-member-form" action="/some-add-url" method="post">
<fieldset class="new-object-fieldset" title="New team member">
<legend>New team member</legend>
<label for="new_team_member_name">Add new</label>
<input type="text" name="new_team_member_name" title="Add member" class="new-object-text-box" />
<button type="submit" name="new_team_member" value="new_team_member" class="submit-button">+</button>
<div id="help-new"></div>
</fieldset> <!-- New team member -->
</form>
<!-- ... -->
and the ruby looks like:
post '/:team_id/team-members.json' do
logger.info("Add team member (json): #{params}")
end
However, the sinatra server only shows params[:team_id], without the name parameter on the teamMembers.create line. Am I doing something stupid in backbone? Not initialising something properly?
I've looked at http://documentcloud.github.com/backbone/#Collection-create,
http://documentcloud.github.com/backbone/docs/todos.html, http://liquidmedia.ca/blog/2011/01/backbone-js-part-1/, http://liquidmedia.ca/blog/2011/01/an-intro-to-backbone-js-part-2-controllers-and-views/ and https://gist.github.com/1655019, but I can't seem to find any answers there. I feel like I've done something stupid, but just can't see it!
It turns out, it was me not knowing how to extract json parameters in sinatra properly. From this site: http://mini.softwareas.com/posting-json-to-a-sinatra-mongodb-service, I found out I had to use request.body.read.to_s instead of the params hash ie,
post '/:team_id/team-members.json' do
request_body = JSON.parse(request.body.read.to_s)
team_member_name = request_body["name"]
# ...
end
I had the same problem. I am on PHP, though. Since Backbone sends POST data not in a query string, but rather in a plain JSON string, the data is not available thru $_POST. To read the Backbone POST data:
// the 'true' param returns an array rather than an object
$post = json_decode(file_get_contents('php://input'), true);
You can also read it directly from $HTTP_RAW_POST_DATA.

Resources