2017-03-04 50 views
3

我試圖將$ compile注入到我的指令中,所以我可以在將指令附加到div之前編譯指令。現在,$ compile是不確定的,我注入錯了嗎?我使用ES6 /角1.5.x的

import MyController from './mycontroller'; 

    class MyDirective { 
     constructor($compile) { 
     this.restrict = 'A'; 
     this.scope = {}; 

     this.controller = MyController; 
     this.controllerAs = 'vm'; 
     this._$compile = $compile; 
    } 

    link(scope, element) { 
     let div = angular.element(document.getElementById('targetDiv')); 

     // $compile is undefined 
     let compiled = this._$compile("<another-directive></another-directive>")(scope)); 
    } 

     static directiveFactory($compile){ 
     MyDirective.instance = new MyDirective($compile); 
     return MyDirective.instance; 
     } 
    } 

    MyDirective.directiveFactory.$inject = ['$compile']; 

    export default MyDirective.directiveFactory; 
+1

我相信你必須將它注入MyDirective而不是指向directiveFactory。 –

回答

1

我也面臨類似的問題,與ES6風格,大量的奮鬥之後,我想通了,下面的工作模式。希望這也能解決你的問題。 I

this使用ES6風格的指令的內部鏈接函數將爲空。有家屬注入,並與ES6風格的指令工作,請按以下方式:

import MyController from './mycontroller'; 

class MyDirective { 
    constructor() { 
    this.restrict = 'A'; 
    this.scope = {}; 

    this.controller = MyController; 
    this.controllerAs = 'vm'; 
} 

link(scope, element, attr, ctrl) { 
    let div = angular.element(document.getElementById('targetDiv')); 

    let compiled = ctrl.$compile("<another-directive></another-directive>")(scope)); 
} 

    static directiveFactory(){ 
    MyDirective.instance = new MyDirective(); 
    return MyDirective.instance; 
    } 
} 

export default MyDirective.directiveFactory; 

而且在mycontroller.js,注入$編譯服務並將其綁定到控制器的內部構造的實例。以下是示例代碼片段:

export default class MyController { 
    constructor($compile) { 
     ... 
     this.$compile = $compile; 
     ... 
    } 

    ... 
} 

MyController.$inject = ['$compile'];