Inject dependency to the angularjs directive using typescript

前端 未结 2 2091
谎友^
谎友^ 2020-12-31 22:27

Lets say I have a simple angular directive that looks like this:

app.directive(\'setFocus\', [\'$timeout\', function($timeout) {
return {
    restrict: \'AC\         


        
2条回答
  •  盖世英雄少女心
    2020-12-31 22:27

    To avoid all the factory boilerplate (and the constructor array at all), I recently wrote a small library (currently as a test project), that make the definition of directives very simple (controller and template omitted here):

    @Directive('userRank')
    export class UserRankDirective implements ng.IDirective {
    
        controller = UserRankDirectiveController;
        restrict = 'A';
        template = template;
        //controllerAs: 'ctrl', set as default
        replace = true;
        scope = {
            user: '=userRank'
        }
    
        constructor($q: ng.IQService) {
            console.log('Q service in UserRankDirective:', $q);
        }
    
    }
    

    It uses decorators like @Directive and a customized version of the TypeScript compiler that make interfaces metadata available at runtime (so ng.IQService can be translated to '$q' and injected in the constructor array). No more app.directive(...) boilerplate: everything is done in decorators :) You can give a look at the sample application code here

提交回复
热议问题