2

I have a datepicker within a form. I would like to set one format for the view but apply a different format to the model value (which is sent to an API). In simple terms I want the user to see 'dd/mm/yyyy' but need the date to be sent in ISO format.

This is my directive:

app.directive('standardDatepicker', function($timeout) {
return{
    restrict: 'A',  
    require : '^ngModel',
    link: function(scope, element, attrs, ngModel, ngModelCtrl){
            element.datepicker({
                format: "dd/mm/yyyy",
                autoclose: true,
            }).on('changeDate', function(e) {
                ngModel.$viewValue = e.date;    
                ngModel.$render();
            });
    }
  }
});

Is there an easy way to achieve this?

Matt Price
  • 1,371
  • 2
  • 9
  • 19

3 Answers3

0

You should use $formatters and $parsers

function standardDatepicker() {
    return {
        require: 'ngModel',
        link: function ($scope, $elem, $attrs, $ctrl) {

            var ngModelCtrl = $ctrl;

            ngModelCtrl.$formatters.unshift(function (value) {
                return value.format('YYYY');
            });

            ngModelCtrl.$parsers.unshift(function (value) {
                return value.format('YYYY-MM-DD');
            });

        }
    }
}
gyc
  • 4,300
  • 5
  • 32
  • 54
0

There are $parsers and $formatters to convert a value. Visit https://stackoverflow.com/a/22843592/2224277 for more information

Community
  • 1
  • 1
0

I ended up using the $parsers as follows. Thanks for all the contributions.

app.directive('standardDatepicker', function($timeout, dateFilter) {
return{
    restrict: 'A',  
    require : 'ngModel',
    link: function(scope, element, attrs, ngModel, ngModelCtrl){
            element.datepicker({
                format: "dd/mm/yyyy",
                autoclose: true,
            }).on('changeDate', function(e) {
                ngModel.$parsers.push(function(viewValue){
                    var isoDate = moment(e.date).format('YYYY-MM-DD');
                    return isoDate;
                });
            });
       }
    }
});
Matt Price
  • 1,371
  • 2
  • 9
  • 19