我正在尝试将$编译到我的指令中,因此我可以在将其附加到DIV之前编译指令。现在,$编译是未定义的,我会注入错误吗?我正在使用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;
我在挣扎中也面临着类似的ES6样式问题,我发现了以下工作模式。希望这也能解决您的问题。我
this
使用ES6样式的指令的内部链接功能为null。要以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
中,注入$编译服务并将其绑定到Controller的实例内部构造函数。以下是样本片段:
export default class MyController {
constructor($compile) {
...
this.$compile = $compile;
...
}
...
}
MyController.$inject = ['$compile'];
您可以简化myDirective类中的A解决方案:
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'];