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.
I think that I found better solution for this. You can use your own parser for datepickerPopup directive. Example which works for me (you have to add this directive to the application):
angular.module('myApp')
.directive('datepickerPopup', function (){
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function toModel(date) {
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
});
}
}
});
Each when you will select the date on date picker you will have the String object with formatted date: 'yyyy-MM-dd'. Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With