core
core

Reputation: 33087

AngularJS event propagation--siblings?

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?

Upvotes: 12

Views: 8465

Answers (3)

alehro
alehro

Reputation: 2208

In my case I'm quite satisfied with:

$rootScope.$broadcast('my event');

Upvotes: 0

Jason Goemaat
Jason Goemaat

Reputation: 29234

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
});

Upvotes: 11

Mathew Berg
Mathew Berg

Reputation: 28750

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)

Upvotes: 16

Related Questions