Search code examples
angularjstypescriptangular-filters

Angular Typescript Filter with Dependencies


I'm trying to figure out how to write an angular filter in typescript with (and this is the part tripping me up) some injection.

Here is what I have so far:

export function StrLimit() {
  return function(input, limit) {
    if (input.length <= limit) {
      return input;
    }
    return $filter('limitTo')(input, limit) + '...';
  }
}

angular.module('myApp').filter('strLimit', StrLimit);

I need to get $filter injected, and I'd like to use native TS for this. Any ideas on how to go about doing this?

Edit: I've seen this question's answer about this topic, but it seems sloppy to use a module, especially because all of the above is already nested inside a module.


Solution

  • In my project we use the $inject property like this:

    export function StrLimit($filter) {
      return function(input, limit) {
        if (input.length <= limit) {
          return input;
        }
        return $filter('limitTo')(input, limit) + '...';
      }
    }
    StrLimit.$inject = ['$filter'];
    
    angular.module('myApp').filter('strLimit', StrLimit);
    

    If you have a typescript class it would be a public static var $inject = ['$filter'];