Subscribers, on the other hand, sign up to listen for
messages with a particular classification.
They also don't know publishers or if there are any publishers for
these particular messages at all.
In angular, the common channel in which these messages communicate over is scope.
Messages that we are speaking about in this design pattern
are called events that can hold data.
There are two types of publishers in angular event handling.
The first one is called emit.
An emit goes up the chain scope.
So if Component_3 wanted to emit an event,
called greet with a data with message equals hi, that event would keep going
up the scope until it reached all the way to the top scope in the application.
The other way to publish messages in the angular, is to broadcast them, and
that's done with the $broadcast method.
Using that method, events go down the chain scope.
So for example, if the very top scope broadcasted an event with the name greet,
and the data with the message equals hi, that event would propagate
all the way down the chain scope to the very last leaf in the scope chain.
The way you subscribe to an event in angular is by calling a special method
on the scope service called $on.
And you provide it the name of the event you're subscribing to and
some handler function that deals with what to do once you caught that event.
You might be wondering the following question, what happens when the target of
your broadcast is not in the direct path of your broadcast code down the chain?
Or the other way around if you're emitting an event the target
is not in the direct scope chain of your event going up the scope chain.
The answer is that you can broadcast your event from the parent scope of
everything in your app, otherwise known as the root scope.
You may not have realized up until now, but the ng-app that we have declared
on some top element like html in our html page is actually the parent
controller to all controllers, directives, and components that live under it.
Angular has a special service called $rootScope that
you can inject into anything in your application in order to refer to
the highest scope in the chain possible, meaning the root scope.
Therefore if you're Component_3 is trying to reach Component_4,
which is not in a direct scope train up the chain tree, you can use the dollar
$rootScope.$broadcast inside of your Component_3.
And what that will do is, that will reach the very top of your scope chain and
will propagate down reaching Component_4.
Note that when you broadcast from the root scope, every single node in your
application gets the event and has a chance to respond to it.
Okay, let's look at some syntax.