Building a generalized Publish-Subscribe service to replace $broadcast, $emit, and $on
In Angular 1, the $emit and $broadcast behaviors were indeed very useful tools. They gave you the ability to send custom events upwards and downwards through the scope tree to any listeners that might be waiting for such an event. This pushed the developer towards a very useful pattern: the ability for many components to be able to transmit events to and from a central source. However, using $emit and $broadcast for such a purpose was grossly inappropriate; they had the effect of feeding the event through huge numbers of scopes only to reach the single intended target.
Note
In the previous edition of this book, the corresponding recipe demonstrated how to build a Publish-Subscribe service that used the $emit and $rootScope injection. The version in this recipe, although different in a handful of ways, achieves similar results in a substantially cleaner and more elegant fashion.
It is preferable to create...