如何扩展或覆盖 angularjs 中的现有过滤器? [英] How to extend or override existing filters in angularjs?

查看:23
本文介绍了如何扩展或覆盖 angularjs 中的现有过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以扩展现有的标准"过滤器(datenumberlowercase 等)?就我而言,我需要从 YYYYMMDDhhmmss 格式解析日期,因此我想扩展(或覆盖)date 过滤器,而不是编写自己的过滤器.

Is it possible to extend existing "standard" filters (date, number, lowercase etc)? In my case I need to parse date from YYYYMMDDhhmmss format so I'd like to extend (or override) date filter instead of writing my own.

推荐答案

我不确定我是否正确理解您的问题,但如果您想扩展现有过滤器的功能,您可以创建一个新过滤器来装饰现有过滤器一.示例:

I'm not sure if I understand your question correctly, but if you would like to extend functionality of existing filters you could create a new filter that decorates an existing one. Example:

myApp.filter('customDate', function($filter) {
    var standardDateFilterFn = $filter('date');
    return function(dateToFormat) {
     return 'prefix ' + standardDateFilterFn(dateToFormat, 'yyyyMMddhhmmss');
    };
});

然后,在您的模板中:

{{now | customDate}}

综上所述,如果您只是想根据给定的格式设置日期格式,可以使用现有的日期过滤器来完成:

Having said the above, if you simply want to format a date according to a given format this can be done with the existing date filter:

{{now | date:'yyyyMMddhhmmss'}}

这是说明这两种技术的有效jsFiddle:http://jsfiddle.net/pkozlowski_opensource/zVdJd/2/

Here is the working jsFiddle illustrating both techniques: http://jsfiddle.net/pkozlowski_opensource/zVdJd/2/

请注意,如果未指定格式,AngularJS 将假定这是中等"格式(确切格式取决于语言环境).检查 http://docs.angularjs.org/api/ng.filter:date 了解更多.

Please note that if a format is not specified AngularJS will assume that this is 'medium' format (the exact format depends on a locale). Check http://docs.angularjs.org/api/ng.filter:date for more.

最后一句话:我对您问题的解析自"部分有些困惑.问题是过滤器用于将对象(在本例中为日期)解析为字符串,而不是反之亦然.如果您正在解析表示日期的字符串(来自输入),您将不得不查看 NgModelController#$parsers(检查 http://docs.angularjs.org/guide/forms).

The last remark: I'm a bit confused about the 'parse from' part of your question. The thing is that filters are used to parse an object (date in this case) to string and not vice verse. If you are after parsing strings (from an input) representing dates you would have to look into NgModelController#$parsers (check the "Custom Validation" part in http://docs.angularjs.org/guide/forms).

这篇关于如何扩展或覆盖 angularjs 中的现有过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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