有没有办法可以在链接功能中访问指令对象? 我正在将代码移植到ES6。当我尝试访问其链接函数中的指令对象时,这个失败了。
class myDirective {
constructor($parse) {
//DDO properties
this.restrict = "A";
this.scope = {};
this.controllerAs = "SomeCtrl";
this.controller = "SomeCtrl";
this.bindToController = true;
this.$parse = $parse;
}
link(scope, element, attrs) {
console.log(this); //<== the link function is not called in context of myDirective object and logs "window" instead of myDirective
// Do something with $parse
// This is not working as this.$parse is not available on window obv
let foo = this.$parse("baz");
}
// Create an instance so that we can access this inside link
static directiveFactory($parse) {
myDirective.instance = new myDirective($parse);
return myDirective.instance;
}
}
// Inject dependencies
myDirective.directiveFactory.$inject = ["$parse"];
export default myDirective.directiveFactory;
我尽量避免使用位于类之外的私有变量,并希望有更好的方法来获取指令对象。
感谢。
答案 0 :(得分:2)
卫生署!我刚刚意识到我的静态字段在链接函数中可用(obv!)。
link(scope, element, attrs, ctrl) {
console.log(myDirective.instance); // This now logs my directive instance and I can access its properties.
…
}