use*_*734 6 angularjs typescript
似乎有很多方法可以在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());
}
Run Code Online (Sandbox Code Playgroud)
但是如果我需要注射东西,我不知道该怎么办.说我想要$ 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());
}
Run Code Online (Sandbox Code Playgroud)
正如您在上面所看到的,我不确定如何调用myDirective构造函数并传入$ timeout.
只需指定$timeout为工厂构造函数参数并将其传递即可。
static factory(): ng.IDirectiveFactory {
var directive: ng.IDirectiveFactory =
($timeout:ng.ITimeoutService) => new myDirective($timeout);
directive.$inject = ["$timeout"];
return directive;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3761 次 |
| 最近记录: |