2014-10-09 189 views
1

我在我的应用程序中实现了一个新指令。指令代码:AngularJs + typescript指令依赖注入

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']); 

我probleme是日志和超时总是不确定的......

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); 
} 

感谢您的帮助:)

回答

4

由于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'. 
    }; 
} 

注册指令在角以下的方式。这里ng.IDirectiveFactory实现为匿名函数:

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

这里的角依赖注入工作,因为它承认构造函数的参数名称(为myService)。

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

+0

此解决方案是否适用于缩小?参数名称的依赖性表明它不会。 – 2016-04-21 14:04:44

0

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

什么是为您的指令定义一个控制器,并将相关性注入控制器。之后只需使用此控制器功能。

+0

这不是很好的建议,使用控制器才能访问外部服务。您可以通过将其注入到指令本身的构造函数中来访问注入的链接函数中的服务:'angular.directive('directiveName',function('inject_services_here'){});'这样您就可以使用链接函数来操作DOM和视图模型逻辑的控制器。 – 2015-08-23 20:01:08