2

If I define/instantiate an object foo inside the link function of directive A. What's a way to access the same object from the link function of a separate directive?

2 Answers 2

2

Quote from documenation:

The controller is instantiated before the pre-linking phase and it is shared with other directives (see require attribute). This allows the directives to communicate with each other and augment each other's behavior.

This means that to share data between two directives on the same object or it's children, you'll need to expose foo inside directive A controller, injected with require option in directive B.

The directives would look like this:

.directive("dirA", function () {
    return {
        controller: function ($scope, $element, $attrs) {

        },
        link: function ($scope, $element, $attrs, controller) {
            controller.foo = $attrs.dirA;
        }
    }
})
.directive("dirB", function () {
    return {
        link: function ($scope, $el, $attr, controller) {
            $scope.shared = controller.foo;
        },
        require: "dirA"
    }
})

Working example.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't have enough reputation to comment, so I'll add it here.

Some additional info for someone struggling with the same issue. It depends on where the directives are used in relation to each other.

The ^ prefix means that this directive searches for the controller on its parents (without the ^ prefix, the directive would look for the controller on just its own element).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.