angularjs - Angular Bootstrap 日期选择器多种格式

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

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

最佳答案

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

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
};
});

关于angularjs - Angular Bootstrap 日期选择器多种格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24870750/

相关文章:

javascript - 在 jQuery Datepicker 上使用 onSelect 后,日历将不会显示

angularjs - 使用 ng-model 使用 angularjs/ui-bootstrap 制作 Accordion

html - 使用 bootstrap list-group-item 的 treeview 的 css 边框样式

javascript - 无法加载模板 : uib/template/modal/window. html(HTTP 状态 404 未找到)

angularjs - 在 Mocha 测试套件中触发 AngularJS 指令上的点击事件

javascript - 如何根据 Controller 中定义的数组创建 ng Repeat block

javascript - 引导日期选择器中的日期递增问题

javascript - Angular-UI Bootstrap Datepicker 新日期

Angularjs 列表/详细信息编辑

javascript - 当我使用别名时,AngularJS 中的 Controller 继承不起作用