0

Is it possible to decorate the angular number filter, to return the input unmodified if it is not a number?

<my-tag input-value="{{foo() | number: 2}}"></my-tag>

When foo() would return 1.2345, the value should show 1.23, but when it returns "abcd" it would return just that: "abcd".

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • At first sight, I thought you were right. This would solve my current problem. However I want it to be reusable for the `date` filter, the `currency` filter, etc... without having N instances of the same decoration code. – xtofl Dec 12 '16 at 14:42
  • I did a Fiddle based on `ng-if`, but your question has been locked before I can post my answer... You can [check it here](https://jsfiddle.net/Mistalis/Lwhg1fuv/). – Mistalis Dec 12 '16 at 15:04

1 Answers1

0

If you want to stock with the number filter you can build a decorator as suggested by @Ankh link, i.e:

app.config(['$provide', function($provide) {
  $provide.decorator('numberFilter', ['$delegate', function($delegate) {
    var srcFilter = $delegate;

    var extendsFilter = function() {
      // Put the logic you want here:
      let val = arguments[0];
      if (angular.isNumber(val)) {
        return srcFilter.apply(this, arguments);
      }
      else if (angular.isString(val)) {
        return val;
      }
      else {
        // Or throw an error
        return JSON.stringify(val);
      }
    }

    return extendsFilter;
  }])
}]);

See this plunker.

T.Gounelle
  • 5,953
  • 1
  • 22
  • 32