1

私はes6で書かれた指令を持っています。このディレクティブコントローラにいくつかのサービスを注入する必要があります。うまく作品に使用ES5のすべてのものに、ES6で指令コントローラに注入する方法

function MyDirective() { 

    function controller(commonService) { 
     commonService.doSomething(this.type); 
    }; 
    return { 
     scope: { 
      type: '=' 
     }, 
     restrict: 'E', 
     controller: ['commonService', controller], 
     controllerAs: 'vm', 
     templateUrl: 'myTemplate.html', 
     bindToController: true 
    }; 
} 

angular.module('myApp').directive('myDirective', ['commonService', MyDirective]); 

その方法:ES5に は、私のような何かをするだろう。 ES6にいる間は、私がやる:今

class MyDirective { 

     constructor(commonService) { 

      this.scope = { 
       type: '=' 
      }; 
      this.restrict = 'E'; 
      this.controllerAs = 'vm'; 
      this.templateUrl = 'myTemplate.html'; 
      this.bindToController: true; 
     } 

     controller() { 
      commonService.doSomething(this.type); 
     } 
} 

angular.module('myApp').directive('myDirective', [('commonService') => MyDirective(commonService)]); 

問題がある:私はもはや私のコントローラにcommonServiceを注入することはできません。 私は、コンストラクタ関数で

this.commonService = commonService; 

を使用しようとしましたが、unfortunatlly、私はいくつかの奇妙な理由のために、コントローラ内部の「この」にアクセスすることはできません。

私のcommonServiceをコントローラ関数に挿入するにはどうしたらいいですか、またはコントローラ関数から "this"へのアクセス権を得るにはどうすればよいですか?

ありがとうございます!

答えて

1

1つのオプションは、コントローラをクラスとして定義することです。

The DEMO

class MyDirective { 
 

 
    constructor() { 
 
     this.scope = { 
 
      type: '@' 
 
     }; 
 
     this.restrict = 'E'; 
 
     this.controller = 'myDirectiveCtrl', 
 
     this.controllerAs = 'vm'; 
 
     this.template = ` 
 
      <fieldset> 
 
       myDir type={{vm.type}} 
 
       <br> Service {{vm.serviceType}} 
 
      </fieldset>`; 
 
     this.bindToController = true; 
 
    } 
 
} 
 

 
class MyDirectiveCtrl { 
 
    constructor(commonService) { 
 
     this.commonService = commonService; 
 
    } 
 
    $onInit() { 
 
     this.serviceType = this.commonService.doSomething(this.type); 
 
    } 
 
} 
 
MyDirectiveCtrl.$inject = ['commonService']; 
 

 
angular.module('myApp',[]) 
 
    .directive('myDirective', MyDirective) 
 
    .controller("myDirectiveCtrl", MyDirectiveCtrl) 
 
    .value("commonService", { 
 
    doSomething: (type) => ("--"+type+"--") 
 
    })
<script src="//unpkg.com/angular/angular.js"></script> 
 
    <body ng-app="myApp"> 
 
    <h1>ES6 Directive Demo</h1> 
 
    <my-directive type="IDK"></my-directive> 
 
    </body>

+0

ありがとう!しかし、私は質問があります:あなたは、コントローラのthis.controller = 'myDirectiveCtrl'ディレクティブの本体に割り当てられている場合、なぜコントローラを.controllerを使って明示的に割り当てる必要がありますか? – Yogev

+0

'app.controller'ステートメントは、クラスを[$ controller service](https://docs.angularjs.org/api/ng/service/$controller)のコントローラキャッシュに格納します。 DDOで 'controller'プロパティの文字列形式を使用すると、そのキャッシュからコントローラが注入されることが指定されます。 – georgeawg

関連する問題