加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:00:30 所属栏目:安全 来源:网络整理
导读:让我们说我有一个简单的角度指令,看起来像这样: app.directive('setFocus',['$timeout',function($timeout) {return { restrict: 'AC',link: function(_scope,_element) { $timeout(function() { _element[0].focus(); },0); }};}]); 如何使用Typescript编
让我们说我有一个简单的角度指令,看起来像这样:
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)));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读