12

I understand that $emit sends messages up the DOM tree, and $broadcast sends messages down.

What about sending messages between sibling DOM elements—how do I do that?

core
  • 30,054
  • 41
  • 131
  • 189

3 Answers3

14

It does not send it up the DOM tree. It sends it up the scope tree, so there's no concept of sibling DOM elements when dealing with scopes. What you can do with $emit though is $emit it up to the parent, stop the propagation and then broadcast which all the siblings will pick up (as well as their children)

Mathew Berg
  • 26,908
  • 11
  • 66
  • 86
11

There's no mechanism for sending to scopes with the same parent. Generally you would broadcast from the root scope since your messages should be unique and most scopes would just ignore them. You could broadcast from the parent which should ignore scopes further up the tree and their descendants, but it will still funnel down to all the descendants of the parent, not just the siblings of the scope you are looking at. You could always ignore the message if your parent isn't the scope it was broadcast on:

$scope.$parent.$broadcast('MyUniqueEventName', data);

$scope.$on('MyUniqueEventName', function(event, data) {
    if ($scope.$parent !== event.targetScope) {
        return;
    }
    // do something with data
});
Jason Goemaat
  • 27,053
  • 14
  • 78
  • 109
  • 1
    You just have to be careful with this approach because it tightly couples your code, you must always manually ensure that $scope.$parent is the correct parent, which makes your code less durable. – Jonathan Rowny Mar 25 '15 at 17:37
  • 1
    Very true. For instance if you have this in a repeater, a switch or an if it will create a child scope and the scope you want to broadcast from might easily be the grandparent. – Jason Goemaat May 12 '15 at 21:43
0

In my case I'm quite satisfied with:

$rootScope.$broadcast('my event');
alehro
  • 2,131
  • 2
  • 24
  • 38