当尝试为日期选择器定义多个输入日期格式时,我们似乎遇到只能定义一种格式的问题。如果不满足此格式,则默认为美国化日期格式(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'
答案 0 :(得分: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>
根据评论编辑
删除了隔离范围&amp;将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
};
});