Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access directive object (this) in link function | ES6

Is there a way one can access the directive's object inside its link function? I am porting code to ES6. And this one is failing for me when I try to access the directive object inside its link function.

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;

I try to avoid private variables that sit outside of the class and hope there is a better way to get hold of the directive object.

Thanks.


1 Answers

Doh! I just realised that my static field is available in the link function (obv!).

link(scope, element, attrs, ctrl) {
    console.log(myDirective.instance); // This now logs my directive instance and I can access its properties.
    …
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!