I am using Angular UI datepicker in my project.
The control has an option "datepicker-popup" which allows me to set up te format I want to display the date in. However the date is bound to my model as a date object and not as a formatted string.
The rest of my code simply requires the date as a string in the correct (yyyy-MM-dd) format.
At the moment wehenever I need to use the date, I format it to the correct string before passing it along.
This works for now since The code base is pretty small but is there a better way to somehow bind the date to my model as a string so that someone forgetting to format the date before using it doesn't break the system.
A plunker for the sample code can be found here.
I was thinking maybe I would need to set up a watch or something but was not too sure what the correct solution would be.
No, currently AngularUI and many other frameworks use the Date object to bind information. You need to format the date to a string each time you want it as a string. The way to do this is to create a function like
$scope.getMyDateAsString = function(){
return myDate.toString(); // or however you format your string.
};
Then anytime you want to get the string you can call this function. You CAN create a watcher
$scope.$watch($scope.myDateModel, function(newVal, oldVal){
$scope.myDateAsString = $scope.getMyDateAsString();
});
This way, anytime the datepicker changes value, you change the value of the string.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments