AngularJS event propagation--siblings?
Asked Answered
A

3

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?

Apparatus answered 5/9, 2014 at 16:36 Comment(0)
P
15

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)

Practical answered 5/9, 2014 at 17:21 Comment(0)
M
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
});
Marketable answered 5/9, 2014 at 17:38 Comment(2)
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.Plotkin
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.Marketable
E
0

In my case I'm quite satisfied with:

$rootScope.$broadcast('my event');
Edlyn answered 14/9, 2016 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.