362

Now that the performance difference between $broadcast and $emit has been eliminated, is there any reason to prefer $scope.$emit to $rootScope.$broadcast?

They are different, yes.

$emit is restricted to the scope hierarchy (upwards) - this may be good, if it fits your design, but it seems to me a rather arbitrary restriction.

$rootScope.$broadcast works across all that choose to listen to the event, which is a more sensible restriction in my mind.

Am I missing something?

EDIT:

To clarify in response to an answer, the direction of the dispatch is not the issue I'm after. $scope.$emit dispatches the event upwards, and $scope.$broadcast - downwards. But why not always use $rootScope.$broadcast to reach all the intended listeners?

1

6 Answers 6

1186

tl;dr (this tl;dr is from @sp00m's answer below)

$emit dispatches an event upwards ... $broadcast dispatches an event downwards

Detailed explanation

$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.

$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.

$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).

$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.

5
  • Thanks for the reply. The focus of my question was why to use scope hierarchy as a way to restrict the audience? The audience is already "restricted" in the sense that controllers choose what to listen to. I clarified in the question that I understand perfectly the distinction between $emit and $broadcast, but I don't understand the need for restriction based on scope hierarchy.
    – New Dev
    Commented Jan 26, 2015 at 19:39
  • 3
    @NewDev The reason is because often you have repetition of scopes on the page. If you have two or more scopes representing different instances of data - e.g. a list of patient records on a page, each with its own scope - then it won't work to broadcast from the root an event that is intended for just one of those scopes. Avoiding $rootScope broadcasts where possible allows better reuse.
    – Tim Rogers
    Commented Feb 10, 2015 at 11:40
  • 4
    Nothing you've said is wrong, but a way to generalize it that $emit goes down the document to child scopes and $emit goes up the document to parent scopes. Both will trigger any listeners attached to the current scope.
    – Eric Rini
    Commented Mar 6, 2015 at 16:41
  • 2
    One point is missed. $emit can be cancelled once executed, $broadcast however, cannot be cancelled. Good examples BTW!
    – Swanidhi
    Commented Oct 4, 2015 at 17:33
  • This answer may be outdated. broadcast is not like "screaming parents". Broadcast is the inverse of emit. emit targets parents. broadcast targets children. Which method is "louder" depends on how many parents vs children the broadcaster/emitter itself has. See "Scope Events Propagation" at docs.angularjs.org/guide/scope Commented Jul 17, 2017 at 18:44
106

They are not doing the same job: $emit dispatches an event upwards through the scope hierarchy, while $broadcast dispatches an event downwards to all child scopes.

2
  • 2
    Yes, I noted that in the question (perhaps I could have made it clear about the direction of the dispatch). But I also noted that that is a rather arbitrary restriction. If I can reach my "listener", why can't I always do this downwards from $rootScope?
    – New Dev
    Commented Nov 5, 2014 at 8:16
  • Because an $emit won't affect a scope's child or sibling scopes. These just map to javascript's event propagation types - capturing and bubbling. $broadcast is used for capturing and $emit is used for bubbling. There's a now seemingly ancient quirksmode article that explains the difference pretty well: quirksmode.org/js/events_order.html
    – Alan L.
    Commented Jul 30, 2015 at 17:43
81

I made the following graphic out of the following link: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Scope, rootScope, emit, broadcast

As you can see, $rootScope.$broadcast hits a lot more listeners than $scope.$emit.

Also, $scope.$emit's bubbling effect can be cancelled, whereas $rootScope.$broadcast cannot.

3
  • 26
    I see a lot of arrows. Commented Jul 10, 2016 at 16:12
  • 5
    @MichalStefanow I'm a fan of visual answers :) Commented Aug 29, 2016 at 19:40
  • @mparnisari :. $broadcast(name, args) - Broadcast an event down through the $scope of all children .$emit(name, args) - Emit an event up the $scope hierarchy to all parents, including the $rootScope
    – CodeMan
    Commented Oct 21, 2016 at 10:30
22

enter image description here

$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)

enter image description here $scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.

enter image description here $scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.

The $emit event can be cancelled by any one of the $scope who is listening to the event.

The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.

Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/

In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.

enter image description here

For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html

2
  • A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.
    – Baum mit Augen
    Commented Jun 27, 2017 at 12:34
  • The objective was to provide the working plunker, however, I have added the appropriate description here.
    – Yogesh
    Commented Jun 27, 2017 at 16:36
4

@Eddie has given a perfect answer of the question asked. But I would like to draw attention to using an more efficient approach of Pub/Sub.

As this answer suggests,

The $broadcast/$on approach is not terribly efficient as it broadcasts to all the scopes(Either in one direction or both direction of Scope hierarchy). While the Pub/Sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work.

you can use angular-PubSub angular module. once you add PubSub module to your app dependency, you can use PubSub service to subscribe and unsubscribe events/topics.

Easy to subscribe:

// Subscribe to event
var sub = PubSub.subscribe('event-name', function(topic, data){
    
});

Easy to publish

PubSub.publish('event-name', {
    prop1: value1,
    prop2: value2
});

To unsubscribe, use PubSub.unsubscribe(sub); OR PubSub.unsubscribe('event-name');.

NOTE Don't forget to unsubscribe to avoid memory leaks.

3

Use RxJS in a Service

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

Build a service with RxJS Extensions for Angular.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

Clients can subscribe to changes with DataService.subscribe and producers can push changes with DataService.set.

The DEMO on PLNKR.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.