There are multiple approaches to creating Angular directives in TypeScript. One elegant method involves using 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());
}
However, if you need to inject dependencies such as $timeout, the process becomes more complex:
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();
directive.$inject = ["$timeout"];
return directive;
}
}
angular.module("app")
.directive("myDirective", myDirective.factory());
}
The challenge lies in properly calling the myDirective constructor and passing in $timeout.