【问题标题】:Angular Bootstrap Datepicker Multiple FormatsAngular Bootstrap Datepicker 多种格式
【发布时间】:2014-09-12 07:00:33
【问题描述】:

当尝试为日期选择器定义多个输入日期格式时,我们似乎遇到了只能定义一种格式的问题。如果不满足此格式,则默认为美国化日期格式 (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'

【问题讨论】:

    标签: angularjs datepicker angular-ui-bootstrap angular-bootstrap


    【解决方案1】:

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

    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>
    

    根据 cmets 进行编辑

    删除了隔离范围并将 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
    };
    });
    

    【讨论】:

    • 感谢您的想法。但问题是,这会引发错误:$compile:multidir Multiple Directive Resource Contention,因为这两个指令都有一个独立的范围。
    • 易于修复.. 从此指令中删除隔离范围...检查编辑
    • 如何使用 datepicker-popup 输入文本来实现这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多