Define AngularJS directive using TypeScript and $inject mechanism

后端 未结 9 1700
死守一世寂寞
死守一世寂寞 2020-12-12 15:04

Recently I started refactoring one of the Angular projects I am working on with TypeScript. Using TypeScript classes to define controllers is very convenient and works well

9条回答
  •  失恋的感觉
    2020-12-12 15:45

    Using classes and inherit from ng.IDirective is the way to go with TypeScript:

    class MyDirective implements ng.IDirective {
        restrict = 'A';
        require = 'ngModel';
        templateUrl = 'myDirective.html';
        replace = true;
    
        constructor(private $location: ng.ILocationService, private toaster: ToasterService) {
        }
    
        link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => {
            console.log(this.$location);
            console.log(this.toaster);
        }
    
        static factory(): ng.IDirectiveFactory {
            const directive = ($location: ng.ILocationService, toaster: ToasterService) => new MyDirective($location, toaster);
            directive.$inject = ['$location', 'toaster'];
            return directive;
        }
    }
    
    app.directive('mydirective', MyDirective.factory());
    

    Related answer: https://stackoverflow.com/a/29223360/990356

提交回复
热议问题