alisonmsmith alisonmsmith - 2 months ago 32
Javascript Question

Angularjs: best practice for sharing data between sibling directives via parent controller

I have two directives nested under a single controller. When I hover over an element in the first directive I want to highlight related elements in the second directive. Currently, I emit an event and the data in my first directive:

// on hover
$scope.$emit('highlight', elms);

which the controller listens for and then broadcasts a new event and the data:

$scope.$on('highlight', function (event, elms) {
$scope.$broadcast('highlight-child', elms);

which my second directive listens for:

$scope.$on('highlight-child', function (event, elms) {
// highlight the elements

I guess my main question is if there is a better way for the first directive or controller to tell the second directive to do something.


One alternative would be to have them communicate through a service which you would inject into each.

The service isolates that communication nicely but the advantages are marginal as far as I can see, besides perhaps performance if it is called very frequently.

On top of that I think you could also have them communicate via a shared object on the parent's scope, passing that to each directive's isolate scope.