【发布时间】:2015-05-02 13:18:02
【问题描述】:
有没有一种方法可以在其链接函数中访问指令的对象? 我正在将代码移植到 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;
我尽量避免使用类之外的私有变量,并希望有更好的方法来获取指令对象。
谢谢。
【问题讨论】:
-
我不知道为什么链接没有绑定到正确的变量,所以我认为这是一种解决方法,但是如果你使用传递给链接函数的第四个参数 (
ctrl) -既然你有bindToController,那应该和this一样,不是吗? -
没有。其实不一样。在指令的链接函数中记录
ctrl时,我得到了附加的控制器,但不是从class myDirective()构造的指令对象,例如。this.$parse … -
啊,很公平。您实际上是如何实例化这些指令之一的?我想
new myDirective()? -
import MyDirective from "./myDirective.directive";然后……angular.module("app", []).directive("myDirective", MyDirective).controller(…); -
好吧,老实说,我不太确定 Angular 是如何与类一起工作的,Angular 会调用
new吗?我担心的是它可能只是将它视为一个函数而不是实际实例化它,这可能解释了为什么你有错误的this上下文。如果你将new MyDirective()作为第二个参数传递给.directive会怎样?
标签: angularjs angularjs-directive this ecmascript-6