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

前端之家收集整理的这篇文章主要介绍了使用typescript注入angularjs指令的依赖项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
让我们说我有一个简单的角度指令,看起来像这样:
app.directive('setFocus',['$timeout',function($timeout) {
return {
    restrict: 'AC',link: function(_scope,_element) {
        $timeout(function() {
            _element[0].focus();
        },0);
    }
};
}]);

如何使用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]);

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

试试这种方式:
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());

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

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

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

猜你在找的Angularjs相关文章