Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 967
core Avatar asked Sep 05 '14 16:09

core


2 Answers

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)

like image 105
Mathew Berg Avatar answered Oct 20 '22 05:10

Mathew Berg


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
});
like image 42
Jason Goemaat Avatar answered Oct 20 '22 05:10

Jason Goemaat