gpt4 book ai didi

javascript - 如何使用 Angular 1.3 及更高版本格式化输入日期

转载 作者:行者123 更新时间:2023-12-03 16:55:58 25 4
gpt4 key购买 nike

通过 Ionic 开发移动应用程序,我有这个 HTML:

<input type="date" ng-model="schedule.start"
name="startDate"
date-to-format />

我有这个指令旨在格式化呈现的日期标签在输入中:

.directive('dateToFormat', function ($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, el, attrs, ctrl) {
ctrl.$parsers.push(function (data) {
return data;
});
ctrl.$formatters.push(function (data) {
return $filter('date')(data, 'EEE dd MMMM yyyy');
// error => filter returns a string, not a date object
});
}
};
});

但是,从 Angular 1.3 开始,格式化程序必须返回一个 Date 对象,而不是等效的字符串。

使用该指令的典型错误:

Expected `mon. 07 september 2015` to be a date.

如何使用 Angular 1.3 及更高版本格式化日期?
如果我将 $filter 包裹在 new Date(...) 中,我将丢失自定义格式...

Plunkr 重现问题:http://plnkr.co/edit/eMIHWjtwHSPLxBBYxYu9?p=preview

最佳答案

在这种情况下,最好使用 <input type="text" />而不是 date以获得更好的浏览器兼容性。它还可以防止 Angular 将值强制为 Date。您仍然可以在自定义指令中使用自定义解析器和格式化程序。

.directive('dateToFormat', function ($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, el, attrs, ctrl) {
ctrl.$parsers.push(function (data) {
return new Date(data); // Maybe use some parsing libraries.
});
ctrl.$formatters.push(function (data) {
return $filter('date')(data, 'EEE dd MMMM yyyy');
// Now you can return strings as you like!
});
}
};
});

关于javascript - 如何使用 Angular 1.3 及更高版本格式化输入日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32436882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com