Skip to content

Instantly share code, notes, and snippets.

@Kienz
Created December 30, 2015 12:15
Show Gist options
  • Select an option

  • Save Kienz/3657eae5858e23c1e4ca to your computer and use it in GitHub Desktop.

Select an option

Save Kienz/3657eae5858e23c1e4ca to your computer and use it in GitHub Desktop.
(function () {
'use strict';
/**
* Mapper Model->View (Formatter) und View-> Model (Parser) für ein Date Objekt.
* Im Model wird ein Date-String benötigt und an der View wird ein Date-Objekt benötigt.
* Beispiel:
* Model = "2015-11-21"
* View = `Tue Dec 01 2015 00:00:00 GMT+0100 (Mitteleuropäische Zeit)` (new Date())
*
* An dem Element kann das Datumsformat mit dem Attribut data-dsm-format="..." definiert werden. Der Default ist 'YYYY-MM-DD'.
*/
angular.module('asys')
.directive('dateStringMapper', DateStringMapper);
DateStringMapper.$inject = [
'moment',
'modernizr'
];
/* @ngInject */
function DateStringMapper(moment, modernizr) {
return {
restrict: 'A',
require: 'ngModel',
priority: 1000,
scope: {
modelFormat: '@asysModelFormat',
fallbackFormat: '@asysFallbackFormat'
},
link: function ($scope, $element, $attr, $ngModel) {
var modelFormat = $scope.modelFormat || 'YYYY-MM-DD',
inputDateNotSupportedFormat = $scope.fallbackFormat || 'DD.MM.YYYY';
function toModelWithoutDateSupport(value) {
return moment(value, inputDateNotSupportedFormat).format(modelFormat);
}
function toModel(value) {
return moment(value).format(modelFormat);
}
function toView(value) {
return modernizr.inputtypes.date ? moment(value).toDate() : moment(value, modelFormat).toDate(inputDateNotSupportedFormat);
}
function toViewWithoutDateSupport(value) {
return moment(value, modelFormat).format(inputDateNotSupportedFormat);
}
/**
* Parser have to be executed before angular inputTypeDate directive executed.
* $parsers run in array order (see https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$parsers)
*/
if (!modernizr.inputtypes.date) {
$ngModel.$parsers.unshift(toModelWithoutDateSupport);
}
$ngModel.$parsers.push(toModel);
$ngModel.$formatters.push(toView);
/**
* Formatter have to be executed after angular inputTypeDate directive executed.
* $formatters run in reverse array order (see https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$formatters)
*/
if (!modernizr.inputtypes.date) {
$ngModel.$formatters.unshift(toViewWithoutDateSupport);
}
}
};
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment