Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular directive dependency injection - TypeScript

There seem to be a number of ways to create Angular directives in TypeScript. The neatest I've seen is to use a static factory function:

module app {
    export class myDirective implements ng.IDirective {
        restrict: string = "E";
        replace: boolean = true;
        templateUrl: string = "my-directive.html";

        link: ng.IDirectiveLinkFn = (scope: ng.IScope, el: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
        };

        static factory(): ng.IDirectiveFactory {
            var directive: ng.IDirectiveFactory = () => new myDirective();
            return directive;
        }
    }

    angular.module("app")
        .directive("myDirective", myDirective.factory());
}

But I'm not sure what to do if I need to inject something. Say I'd like $timeout:

module app {
    export class myDirective implements ng.IDirective {
        restrict: string = "E";
        replace: boolean = true;
        templateUrl: string = "my-directive.html";

        constructor(private $timeout: ng.ITimeoutService) {
        }

        link: ng.IDirectiveLinkFn = (scope: ng.IScope, el: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
            // using $timeout
             this.$timeout(function (): void {
             }, 2000);
        }

        static factory(): ng.IDirectiveFactory {
            var directive: ng.IDirectiveFactory = () => new myDirective(); // Uhoh! - What's goes here?
            directive.$inject = ["$timeout"];
            return directive;
        }
    }

    angular.module("app")
        .directive("myDirective", myDirective.factory());
}

As you can see above, I'm not sure how to call the myDirective contructor and pass in $timeout.

like image 250
user888734 Avatar asked Jun 12 '15 19:06

user888734


1 Answers

Just specify $timeout as the factory constructor function argument and pass it through.

   static factory(): ng.IDirectiveFactory {
        var directive: ng.IDirectiveFactory = 
                       ($timeout:ng.ITimeoutService) => new myDirective($timeout); 
        directive.$inject = ["$timeout"];
        return directive;
    }
like image 152
PSL Avatar answered Nov 15 '22 05:11

PSL