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
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"
}
})
Comments
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).