How to extend or override existing filters in angularjs?

后端 未结 2 603
小蘑菇
小蘑菇 2020-11-29 09:19

Is it possible to extend existing \"standard\" filters (date, number, lowercase etc)? In my case I need to parse date from YYYYMMDDhhm

2条回答
  •  一生所求
    2020-11-29 09:39

    I prefer to implement the decorator pattern, which is very easy in AngularJS.
    If we take @pkozlowski.opensource example, we can change it to something like:

     myApp.config(['$provide', function($provide) {
      $provide.decorator('dateFilter', ['$delegate', function($delegate) {
        var srcFilter = $delegate;
    
        var extendsFilter = function() {
          var res = srcFilter.apply(this, arguments);
          return arguments[2] ? res + arguments[2] : res;
        }
    
        return extendsFilter;
      }])
    }])
    

    And then in your views, you can use both.. the standard output and the extended behavior.
    with the same filter

    Standard output : {{ now | date:'yyyyMMddhhmmss' }}

    External behavior : {{ now | date:'yyyyMMddhhmmss': ' My suffix' }}

    Here is a working fiddle illustrating both techniques: http://jsfiddle.net/ar8m/9dg0hLho/

提交回复
热议问题