如何使用NG-模型来格式化日期? [英] How to format a date using ng-model?

查看:105
本文介绍了如何使用NG-模型来格式化日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义为

<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>

在页面加载的出生日期是很好格式化为类似 2009年12月22日。然而,当我进去看看我的&LT;输入&GT; 它显示为周二2009年12月22日00:00:00 GMT-0800(太平洋标准时间) 我的猜测是JS如何呈现日期对象为字符串。

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.

首先,我怎么告诉角度展现在&LT的日期;输入&GT; 作为像 12/22/2009 ?我似乎无法适用 |。过滤器 NG-模型属性里面

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.

其次,只要我编辑日期,甚至保持它在它的原始格式,我的其他文字(在&LT; TD&GT; )似乎不适用 |日期过滤了;它突然改变格式以匹配输入文本框。我如何得到它适用 |日期过滤每次模型更改

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?

相关问题:

  • How do I get my directive to only fire on onchange?
  • How to access arguments in a directive?

推荐答案

使用的形式 HTTP自定义验证://docs.angularjs。组织/引导/表格演示:<一href=\"http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=$p$pview\">http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=$p$pview

使用formaters和解析器指令和 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-模型来格式化日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆