AngularJS Filter with TypeScript and injection

后端 未结 4 1123
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 15:26

Can somebody provide me with an example of how I can create an Angular Filter in TypeScript that uses dependency injection. At the bottom is what I currently have, which is

4条回答
  •  梦毁少年i
    2021-01-12 15:39

    First, you need to use angular.d.ts definition file.

    Then, you simply do the following :

    MyFilter.$inject = ["$log"];
    function MyFilter ($log: ng.ILogService): Function {
      return function(msg: string) {
        $log.log("I'm injected!");
        return msg;
      };
    }
    angular.module("testModule").filter("MyFilter", MyFilter);
    

    $inject property is available in Function thanks to these lines in angular.d.ts:

    // Support for painless dependency injection
    interface Function {
      $inject?: string[];
    }
    

    See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/angularjs/angular.d.ts#L12

提交回复
热议问题