Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a string variable to datepicker control instead of a date object?

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.

like image 638
Osama Javed Avatar asked Feb 13 '23 02:02

Osama Javed


1 Answers

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.

like image 50
Przemek Nowak Avatar answered Apr 09 '23 22:04

Przemek Nowak