LoginSignup
14
14

More than 5 years have passed since last update.

Type Script で Angularjs を書く時に Dependency Injection で困った

Posted at

初めまして!風俗業界という底辺で働くIT土方であります!

さてさて、
TypeScript で Angularjs のディレクティブなんかを書く時、コンストラクタに変数を渡したいですよね。
でも、TypeScript ではコンパイルエラーになってしまう..(x_x)

そんな時、どうしたら良いのか書いてみました。

例えばこんなコード有ります。
カスタムディレクティブで値に入っている文字列をパースしてモデルとするケース


<input type="file" my-directive="foo" />

JavaScriptだとこんな感じ


myModule.directive('myDirective', function($parse){
  return {
    link : function($scope, $element, $attr) 
    {
      //自分のカスタムディレクティブから値を取るだけ
      var ngModel = $parse.attr('myDirective'); 
    }
  };
});

TypeScriptで書こうとすると


class myDirective implements ng.IDirective
{
  public constructor($parse : ng.IParseService){

  }

  public link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs : ng.IAttributes){
    var ngModel = $parse.attr('myDirective');
  }
}
//クラスなのでインスタンスにする
var hoge = new myDirective($parse);

しかし、コンストラクタに $parse を渡したいのですが、この時点ではDIされないので
引数を渡す前の時点で、 $parse は undefined となってしまいます。

そこで!


class myDirective implements ng.IDirective
{
  static parse :  ng.IParseService;

  public constructor($parse : ng.IParseService){
     myDirective.parse = $parse;
  }

  public link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs : ng.IAttributes){
    var ngModel = myDirective.parse.attr('myDirective');
  }

  static factory(): ng.IDirectiveFactory {
    var directive: ng.IDirectiveFactory =
      ($parse :ng.IParseService) => new myDirective($parse);

    //必要なサービスを明示的に指定
    directive.$inject = ["$parse"];
    return directive;
  } 

}
//static なのでこうなる
var hoge = myDirective.factory();

staticなfactoryメソッドから明示的に必要なサービスを指定してあげる事で幸せになれました(^q^)

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14