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?
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?
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)
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
});
In my case I'm quite satisfied with:
$rootScope.$broadcast('my event');
© 2022 - 2024 — McMap. All rights reserved.