Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicating between sibling scopes in Angular

Is this how to correctly communicate between two components that are scope siblings?

  1. Ctrl1 emits event up to parent scope of both Ctrl1 and Ctrl2.
  2. Parent scope listens for emitted event from Ctrl1, then broadcasts another event down to Ctrl2.
  3. Ctrl2 listens for broadcasted event from parent scope.

diagram

like image 485
core Avatar asked Dec 30 '14 17:12

core


People also ask

How do you pass data between siblings in angular 8?

Sharing data between sibling components: Sharing data between siblings can be done by using points 1 and 2. First share data between the child to parent using output decorator and EventEmitter. Once received data in parent component share it to another child component using Input decorator.

What are the scopes in angular?

The Scope in AngularJS is the binding part between HTML (view) and JavaScript (controller) and it is a built-in object. It contains application data and objects. It is available for both the view and the controller. It is an object with available properties and methods.

What is parent scope in AngularJS?

Angular scopes include a variable called $parent (i.e. $scope. $parent ) that refer to the parent scope of a controller. If a controller is at the root of the application, the parent would be the root scope ( $rootScope ). Child controllers can therefore modify the parent scope since they access to it.


1 Answers

Yes, this is how I communicate between sibling scopes in Angular. Typically I think of Ctrl1 as emitting 'up' to all its descendant scopes and 'on' a parent scope listening to the event, the parent scope broadcasting 'down' to all children scopes. In this case, Ctrl2 should have something set up on 'on' to do something once it hears the event.

As a side note, I've done something similar where I've used the rootScope as a centralized event bus where it listens to different children scope's events and then performs some task or broadcasts down again. The children scopes would then be responsible for simply emitting up to the rootScope.

like image 60
wmock Avatar answered Sep 24 '22 06:09

wmock