gpt4 book ai didi

angularjs - Angular 指令依赖注入(inject) - TypeScript

转载 作者:搜寻专家 更新时间:2023-10-30 20:40:34 25 4
gpt4 key购买 nike

似乎有很多方法可以在 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());
}

但如果我需要注入(inject)一些东西,我不确定该怎么做。假设我想要 $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());
}

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

最佳答案

只需将$timeout 指定为工厂构造函数参数并传递给它即可。

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

关于angularjs - Angular 指令依赖注入(inject) - TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30810607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com