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

I am using Angular UI datepicker in my project.

The control has the option "datepicker-popup", which allows me to configure the te format in which I want to display the date. However, the date is tied to my model as a date object, not as a formatted string.

The rest of my code just requires a date as a string in the correct format (yyyy-MM-dd).

At the time I need to use the date, I will format it to the correct string before passing it.

This works now, since the code base is quite small, but there is a better way to associate the date with my model as a string so that someone forgot to format the date before using it, it does not break the system.

A plunker for sample code can be found here.

I thought maybe I would need to set the clock or something else, but not too sure what would be the right solution.

+4
source share
3 answers

No, currently AngularUI and many other frameworks use the Date object to bind information. You need to format the date to the string every time you want it to be in the form of 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.
};

, , .

$scope.$watch($scope.myDateModel, function(newVal, oldVal){
    $scope.myDateAsString = $scope.getMyDateAsString();
});

, , datepicker , .

+2

, . datepickerPopup. , ( ):

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

, , String : "yyyy-MM-dd". , .

+6

, Datepicker Moment.js, :

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

, .

0
source

Source: https://habr.com/ru/post/1538755/


All Articles