您可以使用解析器在将值附加到 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
};
});