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

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

问题描述

是否有可能扩展现有的标准过滤器(日期数量小写等)?
在我来说,我需要解析的为YYYYMMDDhhmmss日期格式,所以我想扩展(或重写)日期过滤,而不是写我自己的。

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');
    }    
});

然后,在你的模板:

and then, in your template:

{{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说明这两种方法:<一href=\"http://jsfiddle.net/pkozlowski_opensource/zVdJd/2/\">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.

最后一句话:我有点困惑的你的问题的一部分的解析。问题是,过滤器用于解析的对象(日期在这种情况下)为字符串,而不是反之亦然。如果您解析字符串(从输入)再presenting后的约会,你就必须寻找到NgModelController#$解析器(中的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天全站免登陆