2

当尝试为 Date Picker 定义多个输入日期格式时,我们似乎遇到了只能定义一种格式的问题。如果不满足此格式,则默认为美国化日期格式 (MM/dd/YYYY)。

例如,如果我们将格式设置为 dd-MM-yyyy,但输入日期为 7/8/09,这将被解释为 2009 年 7 月 8 日。

有没有一种方法可以接受和验证多个日期格式,例如:

'dd-MM-yyyy',
'dd.MM.yyyy',
'dd/MM/yyyy',
'dd-MM-yy',
'dd.MM.yy',
'dd/MM/yy,
'd/M/yy'
4

1 回答 1

2

您可以使用解析器在将值附加到 datepicker 之前对其进行解析

csapp.directive("csDateConverter", function () {

var linkFunction = function (scope, element, attrs, ngModelCtrl) {

    ngModelCtrl.$parsers.push(function (datepickerValue) {
        //convert the date as per your specified format
        var date = moment(datepickerValue, scope.format) 

        //convert it to the format recognized by datepicker
        return date.format("YYYY-MM-DD");
    });
};

return {
    scope: {format: '='}
    restrict: "A",
    require: "ngModel",
    link: linkFunction
};
});

你可以像这样使用它

<datepicker ng-model="dt" cs-date-converter="yyyy.mm.dd"></datepicker>

根据评论编辑

删除了隔离范围并将 scope.format 更改为 attrs.format

csapp.directive("csDateConverter", function () {

var linkFunction = function (scope, element, attrs, ngModelCtrl) {

    ngModelCtrl.$parsers.push(function (datepickerValue) {
        //convert the date as per your specified format
        var date = moment(datepickerValue, attrs.format.toUpperCase()) 

        //convert it to the format recognized by datepicker
        return date.format("YYYY-MM-DD");
    });
};

return {
    restrict: "A",
    require: "ngModel",
    link: linkFunction
};
});
于 2014-07-21T17:20:14.407 回答