似乎有很多方法可以在TypeScript中創建Angular指令。我見過的最好的是使用靜態工廠功能:Angular指令依賴注入 - TypeScript
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());
}
但我不知道如果我需要注入什麼,該怎麼辦。說我想$超時:
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構造器,並通過在$超時。
你爲什麼對角頂分層你自己的模塊?你從這個額外的複雜層面,額外的全局狀態和語義重複中獲得了什麼好處? – yangmillstheory