How to extend or override existing filters in angularjs?

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

<p>Standard output : {{ now | date:'yyyyMMddhhmmss' }}</p>
<p>External behavior : {{ now | date:'yyyyMMddhhmmss': ' My suffix' }}</p>

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

Leave a Comment