我正在尝试将$ 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;
答案 0 :(得分:2)
我也遇到过与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
中,注入$ compile服务并将其绑定到构造函数内的控制器实例。以下是示例代码段:
export default class MyController {
constructor($compile) {
...
this.$compile = $compile;
...
}
...
}
MyController.$inject = ['$compile'];
答案 1 :(得分: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'];