2

I wanted to use an input[date] inside a form to enable users to use the modern browsers' support, without using a javascript datepicker. For the ones who're using not supporting browsers, I'v set ui-mask. Both work together. I use the french format (dd/mm/YYYY).

<input type="date" ng-model="myDate" ui-mask="99/99/9999">
$scope.myDate = new Date("2016-02-12"); // works
$scope.myDate = "12/02/2016"; // Doesn't...

In an empty form, no problem, Angular accept it. But with a filled form, Angular expects a date format I don't want : YYYY-mm-dd (javascript date object).

I can't understand why Angular only provides support that format, and not others like french format. Because I want the input[date] to show the french format, not the standard one !

Many modern browsers provides interesting support for dates, I can't understand why Angular waste that.

Or maybe I missed something ?

Ecorce
  • 123
  • 2
  • 11

1 Answers1

0

To achieve your goal need to use momentJs and ngModel $parsers and $formatters. Below some code and JSFiddle example:

In your controller you prepare some string value in french date format:

$scope.myDate= '12/02/2016';

In view you set this value to ngModel attribute of input[type=date] element:

<input class="form-control" type="date" ng-model="myDate">

You need to create new directive, it can be assigned to input element:

.directive('input', function(dateFilter) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function(scope, element, attrs, ngModel) {
            if (
                'undefined' !== typeof attrs.type && 'date' === attrs.type && ngModel
            ) {
                ngModel.$formatters.push(function(modelValue) {
                    return moment(modelValue, "DD/MM/YYYY").toDate();
                });

                ngModel.$parsers.push(function(viewValue) {
                    return moment(viewValue).format("DD/MM/YYYY");
                });
            }
        }
    }
})

New function in $formatters array modifies your myDate to javascript date object (with moment parser it's pretty simple). New function in $parsers array modifies value of input element back to french formatted date string.

This solution provides two way binding between your myDate and input[type=date] element. :)

Look at JSFiddle exaple

Enver Dzhaparoff
  • 4,341
  • 3
  • 19
  • 21
  • Mmmm, not exactly what I wanted. I want the input to show a french format and provide to Angular an iso date if that's what it needs. – Ecorce Feb 15 '16 at 08:26