AngularJS Filter with TypeScript and injection

后端 未结 4 1111
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  执念已碎
    2021-01-12 15:58

    It's generally better to use a function+module instead of a class when writing an Angular filter. You can structure the code like this:

    function FriendlyDateFilter($filter) {
        return function (s: string): string {
            /* Your logic here */
        }
        /* Helper logic here */
    }
    module FriendlyDateFilter {
        export var $inject = ['$filter'];
    }
    
    angular.module("ReadingLog").filter("FriendlyDateFilter", FriendlyDateFilter);
    

    You could also place both FriendlyDateFilter declarations inside another module if you're trying to avoid adding too much to the global scope.

提交回复
热议问题