2017-07-18 58 views
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

一種選擇是將控制器定義爲一個類。

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

謝謝!我確實有一個問題:爲什麼你需要使用.controller明確地分配控制器,如果你在指令的body中有this.controller ='myDirectiveCtrl'賦值? – Yogev

+0

'app.controller'語句將類存儲在[$ controller service](https://docs.angularjs.org/api/ng/service/$controller)的控制器緩存中。在DDO中使用'controller'屬性的字符串形式指定要從該緩存注入控制器。 – georgeawg