Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

You can format your dates after picking, using Cordova Plugin Datepicker and Moment.js, this solution works for me:

$scope.pickSinceDate = function(){
    pickDate($scope.filter.since).then(function(date){
        $scope.since = moment(date).format('YYYY-MM-DD');
    });
});

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top