将$compile注入到未定义的指令中

3
我想在我的指令中注入$compile,以便在将其附加到div之前编译指令。目前,$compile未定义,我是否注入有误?我正在使用ES6 / Angular 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中。 - Gonzalo.-
2个回答

2

我也遇到了ES6样式的类似问题,经过长时间的努力,我找到了以下有效的解决方案。希望这也能解决你的问题。

在使用ES6样式的指令链接函数中,this会变成null。为了在指令中注入并使用依赖项,按照以下样式:

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中,引入$compile服务,并在构造函数中将其绑定到控制器的实例上。以下是示例代码:

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

   ...
 }

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

0

您可以在MyDirective类中简化解决方案:

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

 controller($compile){
   this.$compile = $compile;
 }

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接