加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular指令依赖注入 – TypeScript

发布时间:2020-12-17 07:11:07 所属栏目:安全 来源:网络整理
导读:似乎有很多方法可以在TypeScript中创建Angular指令.我见过的最好的是使用静态工厂函数: module app { export class myDirective implements ng.IDirective { restrict: string = "E"; replace: boolean = true; templateUrl: string = "my-directive.html";
似乎有很多方法可以在TypeScript中创建Angular指令.我见过的最好的是使用静态工厂函数:

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());
}

但是如果我需要注射东西,我不知道该怎么办.说我想要$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,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());
}

正如您在上面所看到的,我不确定如何调用myDirective构造函数并传入$timeout.

解决方法

只需指定$timeout作为工厂构造函数参数并传递它.

static factory(): ng.IDirectiveFactory {
        var directive: ng.IDirectiveFactory = 
                       ($timeout:ng.ITimeoutService) => new myDirective($timeout); 
        directive.$inject = ["$timeout"];
        return directive;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读