【问题标题】:AngularJs + typescript directives dependency injectionAngularJs + typescript 指令依赖注入
【发布时间】:2014-12-04 14:54:53
【问题描述】:

我尝试在我的应用程序中实现一个新指令。指令代码:

module Myapp.NV.Directives {

export interface placeHolderScope extends ng.IScope {
    txt: string;
}

/**
* PlaceHolder
*
*  @class
*  @classdesc This directive is use to simulate placeholder HTML5 attributes
*/
export class PlaceHolder implements IDirective {
    static $inject = ['$log','$timeout'];
    constructor($log: ng.ILogService, $timeout: ng.ITimeoutService) {
        var txt;
        var directive: any = {
            restrict: "A",
            scope: { txt: "@ngPlaceholder" },
            link: function (scope: placeHolderScope, elem: ng.IAugmentedJQuery, attrs: ng.IAttributes, $log: ng.ILogService, $timeout: ng.ITimeoutService) {
                console.log($log);
                console.log($timeout);
            }
        }
        return directive;
    }
}
}

 Myapp.NV.registerDirective('PlaceHolder', ['$log', '$timeout']);

我的问题是日志和超时总是未定义...

static $inject = ['$log','$timeout'];

不会工作...

registerDirective函数代码:

export function registerDirective(className: string, services = []) {
    var directive = className[0].toLowerCase() + className.slice(1);
    services.push(() => new Myapp.NV.Directives[className]());
    angular.module('Myapp.NV.Directives').directive(directive, services);
}

谢谢你的帮助:)

【问题讨论】:

    标签: javascript angularjs dependency-injection typescript


    【解决方案1】:

    正如 boindill 在原始答案中指出的那样,依赖项是通过 TypeScript 构造函数注入的,而不是通过链接函数。

    这是我的解决方案,myDirective 依赖于 myService:

    export class MyDirective implements ng.IDirective {
        static $inject = ["myService"];
    
        constructor(private myService: IMyService) {
        }
    
        restrict = "A";
    
        scope = {};
    
        link = (scope: IMyScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) => {
            // directive implementation
            // Access myService through 'this.myService'.
        };
    }
    

    通过以下方式在 Angular 中注册指令。这里 ng.IDirectiveFactory 被实现为匿名函数:

    angular.module("app", []).directive("myDirective", (myService: IMyService) => {
        return new MyDirective(myService);
    });
    

    这里 Angular 依赖注入有效,因为它可以识别构造函数参数名称 (myService)。

    为了确保在生成的 JavaScript 被缩小时依赖注入仍然能够识别依赖项,静态 $inject 属性在字符串数组中提供了它们的名称。与普通 JavaScript 一样,确保构造函数参数和 $inject 数组成员的顺序相同。

    【讨论】:

    • 此解决方案是否适用于缩小?对参数名称的依赖表明它不会。
    【解决方案2】:

    您不能在指令的link 函数中注入依赖项。链接函数有一个固定的签名function link(scope, element, attrs) { ... } 这取自官方的 angularjs 文档。

    你要为你的指令定义一个控制器并将依赖注入到控制器中。之后只需使用此控制器功能。

    【讨论】:

    • 这不是一个好建议,使用控制器来访问外部服务。您可以通过将它们注入指令本身的构造函数来访问链接函数中注入的服务:angular.directive('directiveName', function('inject_services_here') {}); 这样您就可以使用链接函数来操作 DOM 和视图模型逻辑的控制器。
    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 2014-11-21
    • 2016-03-17
    相关资源
    最近更新 更多