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

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());
}
}

Related

Error displaying date using angularfire and firebase

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.

date format is giving different result in angularjs

<div ng-repeat="n in ShoeDetails.txnList">
<div ng-if="n.statusNo == 21">
<p ng-bind="n.timeStamp | date:'MM/dd/yyyy'"></p>
</div>
</div>
i'm trying to update the date format using angularjs,but i'm getting a result like this /Date(1459418939990+0530)/,unable to understand what was this,any help appreciated
Those are ticks. You need to parse and convert it to a date object.
Either do the below in the frontend using javascript, or do it in C#.
var myDate = "/Date(1459418939990+0530)/";
var regex = /-?\d+/;
var match = regex.exec(myDate);
var date = new Date(parseInt(match[0]));

updating a single value in localstorage

So i've got this piece of code to update the date and time a person leaves in localstorage
$scope.visitorout = function(){
var dateout1 = new Date();
var signout = JSON.parse(localStorage["allVisitors"]);
for(var i=0;i<signout.length;i++)
if (signout[i].id===signout[i].id) signout[i].dateout = dateout1;
localStorage["allVisitors"] = JSON.stringify(signout);
};
but whenever i call the function, it changes all the values of dateout for every single thing in local storage but i only want it to change just one
I have modified the code to this:
$scope.visitorOut = function(id){
var allVisitors = JSON.parse(localStorage["allVisitors"]);
var visitor;
for(var i=0; i<allVisitors.length; i++){
visitor = allVisitors[i];
if (allVisitors[i].id === visitor.id) {
visitor.dateout = new Date();
console.log(visitor.id)
break;
}
}
localStorage["allVisitors"] = JSON.stringify(allVisitors);
};
It updates the 'dateout' but for just the same item in localstorage and the console.log displays the same id each time...
<div class="list">
<a class="item item-icon-left item-icon-right" ng-repeat="visit in visits | orderBy: '-date'" ng-click="visitorOut(id); closesignout()" ng-hide="visit.hide">
<i class="icon ion-person"></i>
{{visit.fname}} {{visit.lname}}
<i class="icon ion-log-out" ng-click="hideMe(visit)"></i>
This code looks like a bug. You are comparing an object to itself (which will always be true):
if (signout[i].id===signout[i].id)
This function needs to know which visitor to update. Wherever you're calling this function, you need to pass in at least the userId (if not the full user object) something like: $scope.visitorOut(user.id) or from html: <myElement ng-click="visitorOut(user.id)" />
$scope.visitorOut = function(userId){
var allVisitors = JSON.parse(localStorage["allVisitors"]);
var visitor;
for(var i=0; i<allVisitors.length; i++){
visitor = allVisitors[i];
if (visitor.id === userId) {
visitor.dateout = Date.now();
break;
}
}
localStorage["allVisitors"] = JSON.stringify(signout);
};
Note that I've used Date.now() here instead of new Date(). It's much easier to work with timestamps than Dates if you're going to stringify it. A timestamp can be converted to a Date like this:
var myDate = new Date(visitor.dateOut);
But if you want to convert a stringified date back to a Date object... it gets complicated (click).
I also changed the variable names a bit. Camelcase is a useful naming convention that aides readability, and from reading the rest of the code the signout variable seems to actually be an array of visitor objects, not an array of signouts, so I renamed that too.

Calling an angularjs function during controller init

I have a large amount of code that I inherited. It is working according to the original spec, so although it may or may not be the "right" way of doing things, it does work and I'd prefer not to mess with it. (I am VERY new to angular, and under a tight deadline - I don't have time right now to "fix" things that aren't broken, even if they're not being done the "correct" way.)
I have a checkbox and a group of address fields. When the checkbox is checked, a function runs that populates the address fields.
<input id='as_check' type="checkbox" ng-model='model.prepop_addr' ng-change="model.handlePrepopAddress()">
<input type="text" placeholder="Address 1" required ng-model='model.payment.addr1'/>
<input type="text" placeholder="Address 2" ng-model='model.payment.addr2'/>
<input type="text" placeholder="City" required ng-model='model.payment.city'/>
<input type="text" placeholder="State" required ng-model='model.payment.state'/>
<input type="text" placeholder="Zip" required ng-model='model.payment.zip'/>
In my controller, I have a function called handlePrepopAddress():
model.handlePrepopAddress = function () {
if (model.prepop_addr) {
console.log("prepop is true");
var del_addr = $window.user_state.deliveryAddress;
model.payment.addr1 = del_addr.address;
model.payment.addr2 = null;
model.payment.city = del_addr.city;
model.payment.state = del_addr.state;
model.payment.zip = del_addr.zip;
} else {
console.log("prepop is false");
model.payment.addr1 = null;
model.payment.addr2 = null;
model.payment.city = null;
model.payment.state = null;
if (!model.payment.saved) {
model.payment.zip = null;
}
}
return true;
};
When I click the checkbox, this runs correctly and updates the various fields. Requirements have changed, and the client now wants the checkbox defaulted to checked, which would then default the values of the fields. Rather than duplicating code, I thought I'd be able to just run the function at the start of the controller, like this:
place_order.controller('AsCreditCardCtrl', ['$scope', 'PaymentModel', function ($scope, model) {
$scope.model = model;
model.prepop_addr = true;
model.handlePrepopAddress();
}]);
The function is running, as the console.log statements I have in the function are running. But the view is not updating; the checkbox is visibly unchecked and the fields are empty aside from the initial placeholder values.
What am I missing? How can I make the function update the view?
You can try
var i= model.handlePrepopAddress();
It might work.

AngularJS: SetValidity within an ng-repeat

I want to check that an input value is valid, (i.e. if someone is spending at least 25 cents on a candy from a list of candies), and if not, tag that input as $invalid, so the form doesn't get submitted.
<form novalidate name="candyForm">
<div ng-repeat="candy in candies">
<input name="candyCost" type="text" ng-model="candy.cost" required>
<div class="error" ng-show='checkEnoughMoney()'>You only have 1 dollar to spend</div>
<div class="error" id="candyError{{$index}}">You must spend at least 25c per candy</div>
</div>
</form>
The checkEnoughMoney() is:
$scope.checkEnoughMoney = function() {
var total = 0;
for(var i = 0; i < $scope.candies.length; i++) {
var amount = parseFloat($scope.sweets[i].cost) || 0;
total = total + amount;
if((parseFloat(amount) >= 25) && (parseFloat(amount) <= 100)) {
$("#candyError" + i).hide();
}
else {
$("#candyError" + i).show();
}
}
if(total > 100) {
$scope.candyForm.candyCost.$setValidity('candyForm.candyCost',false);
return true;
}
else {
$scope.candyForm.candyCost.$setValidity('candyForm.candyCost',true);
return false;
}
};
Setting the $scope.candyForm.candyCost to true or false works here as it affects all the instances if candies, which is great, as it needs to. But how do I make the single instance invalid if the person has entered less than 25 cents or more than 100 cents?
As you can see, I have cheated to make the 25>=cost>=100 messages show when they should, but the form is still submitting, as the input is not being set to invalid. If I try $scope.candies[index].setValidity("cost", false), it throws an error, as the parent scope can't access the scope inside the ng-repeat. Is there any way to get around this?
Here's an example of handling forms in Angular that should take care of your problem.
http://docs.angularjs.org/cookbook/advancedform
I prefer to setup a controller fn to handle requests and pass those through a service.

Resources