如何使用 ng-model 格式化日期? [英] How to format a date using ng-model?
问题描述
我有一个输入定义为
<input class="datepicker" type="text" ng-model="clientForm.birthDate" />
被操纵以显示在页面上的其他地方:
Which is rigged up to be displayed elsewhere on the page:
<tr>
<th>Birth Date</th>
<td>{{client.birthDate|date:'mediumDate'}}</td>
</tr>
当页面加载时,出生日期的格式很好,类似于 Dec 22, 2009
.但是,当我查看我的 时,它显示为
Tue Dec 22 2009 00:00:00 GMT-0800 (Pacific Standard Time)
我猜是这样JS 将 Date
对象呈现为字符串.
When the page loads the birth date is nicely formatted as something like Dec 22, 2009
. However, when I look inside my <input>
it's shown as Tue Dec 22 2009 00:00:00 GMT-0800 (Pacific Standard Time)
which I guess is how JS renders Date
objects as strings.
首先,我如何告诉 Angular 在 中显示日期,例如
12/22/2009
?我似乎无法在 ng-model
属性中应用 |filters
.
Firstly, how do I tell Angular to show the date in the <input>
as something like 12/22/2009
? I can't seem to apply |filters
inside the ng-model
attribute.
其次,一旦我编辑日期,即使将其保留为原始格式,我的其他文本(在 <td>
内)似乎并不适用 |日期
过滤器了;它突然改变格式以匹配输入文本框的格式.我如何让它在每次模型更改时应用 |date
过滤器?
Secondly, as soon as I edit the date, even keeping it in it's original format, my other text (inside the <td>
) doesn't seem to apply the |date
filter anymore; it suddenly changes formats to match that of the input textbox. How do I get it to apply the |date
filter every time the model changes?
相关问题:
推荐答案
使用表单的自定义验证 http://docs.angularjs.org/guide/forms 演示:http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview一个>
Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview
使用格式器和解析器以及 MomentJS )
Directive using formaters and parsers and MomentJS )
angModule.directive('moDateInput', function ($window) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
var moment = $window.moment;
var dateFormat = attrs.moDateInput;
attrs.$observe('moDateInput', function (newValue) {
if (dateFormat == newValue || !ctrl.$modelValue) return;
dateFormat = newValue;
ctrl.$modelValue = new Date(ctrl.$setViewValue);
});
ctrl.$formatters.unshift(function (modelValue) {
if (!dateFormat || !modelValue) return "";
var retVal = moment(modelValue).format(dateFormat);
return retVal;
});
ctrl.$parsers.unshift(function (viewValue) {
var date = moment(viewValue, dateFormat);
return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
});
}
};
});
这篇关于如何使用 ng-model 格式化日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!