'Is it possible to use angularjs internal 'createDateParser' in directive?

Angular.js internally uses createDateInputType to handle date and time specific input elements with ngModel binding. In this createDateParser is used to parse date/times. for example:
definition of the input[date]:

'date': createDateInputType('date', DATE_REGEXP,
    createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
    'yyyy-MM-dd'),

definition of the input[time]:

'time': createDateInputType('time', TIME_REGEXP,
    createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
   'HH:mm:ss.sss'),

basically it would be possible to change the used date and time formating in the source. but there is no api/option to specify other formats. (i think that would be a good fit for ngModelOptions)

now i just want to extend on the original behavior with an directive and add a parser / formatter that uses a user specified format string. For this i need similar functionality like the createDateParser - so is it possible to use these internal function in a directive?


alternative solution would be to include moment.js as parsing/formatting library.

i have setup a Plunker to demonstrate this - using moment.js - but it would be better to not have to include a external lib if the functionality is somewhere in the core... (the directive only gets active if the browser does not natively support date or time)

iam just adding a parser and a formatter at the first position with array.unshift() so for the formatters it will be called last. For the parser it will be called first.
The formatter just converts the angular/iso formatted string back to a date-object and formats it according the user-given formatString.

ctrl.$formatters.unshift(function(value) {
    if (value) {
        var tempDate = moment(value, format_internal);
        var intDateFormatedString = tempDate.format(scope.formatString);
        return intDateFormatedString;
    }
});

The Parser works the same only in the other direction and with some validating.

ctrl.$parsers.unshift(function(viewValue) {
    var resultString;
    if (viewValue) {
        // momentjs with strict parsing
        var tempDate = moment(viewValue, scope.formatString, true);
        if ( tempDate.isValid() ) {
            ctrl.$setValidity("userInput", true);
             // return as string with internal angular expected format
            resultString = tempDate.format(format_internal);
        }
    }
    return resultString;
});

only partly related:

How to manually rerun formatter chain in angularjs directive with ngModel?

hopefully the style of the 'question' is ok - iam not sure if i have found the right focus.. eventually it would be better to split it up somehow?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source