使用typescript注入angularjs指令的依赖项

P3a*_*uts 7 angularjs typescript angularjs-directive

假设我有一个简单的角度指令,如下所示:

app.directive('setFocus', ['$timeout', function($timeout) {
return {
    restrict: 'AC',
    link: function(_scope, _element) {
        $timeout(function() {
            _element[0].focus();
        }, 0);
    }
};
}]);
Run Code Online (Sandbox Code Playgroud)

如何使用Typescript编写它并在链接函数中获得$ timeout访问?我的例子看起来像这样:

/// <reference path="../../reference.ts"/>

class SetFocus{
    constructor() {
        var directive: ng.IDirective = {};
        directive.restrict = 'EA';
        directive.scope = { };        
        directive.link= function ($scope, $element, $attrs) {
        // How can I access $timeout here?

        }
        return directive;
    }
}

directives.directive('setFocus', [SetFocus]);
Run Code Online (Sandbox Code Playgroud)

这可能是一个愚蠢的例子,但它是我想要工作的原则,它在角度链接函数中使用注入的依赖项.

PSL*_*PSL 9

试试这种方式:

class SetFocus implements ng.IDirective {
    //Directive settings
    restrict :string = 'EA';
    scope : any= {};
    //Take timeout argument in the constructor
    constructor(private $timeout: ng.ITimeoutService) {
    }

    link: ng.IDirectiveLinkFn = ($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ng.IAttributes) => {
          //refer to the timeout
          this.$timeout(function() {
            $element[0].focus();
         }, 0);
    }
    //Expose a static func so that it can be used to register directive.
    static factory(): ng.IDirectiveFactory {
       //Create factory function which when invoked with dependencies by
       //angular will return newed up instance passing the timeout argument
        var directive: ng.IDirectiveFactory = 
              ($timeout:ng.ITimeoutService) => new SetFocus($timeout);
        //directive's injection list
        directive.$inject = ["$timeout"];
        return directive;
    }
}

directives.directive('setFocus', SetFocus.factory());
Run Code Online (Sandbox Code Playgroud)

这可能是你现在拥有它的方式的一个问题.因为指令工厂没有新建,所以它的构造函数将this作为全局对象执行.这样你就不会有一个巨大的构造函数,并且可以用适当的类ey方式编写它.

如果您注入了许多依赖项而不是在工厂中重复参数,那么您也可以这样做:

  var directive: ng.IDirectiveFactory =
            (...args) => new (SetFocus.bind.apply(SetFocus, [null].concat(args)));
Run Code Online (Sandbox Code Playgroud)