2014-10-09 190 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