Tuesday, June 7, 2016

Understand $emit, $broadcast in Angularjs



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


$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.



$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.


  1. var app = angular.module('myapp', []);
  2. app.controller("mainctrl", function ($scope) {
  3. $scope.raise = function (msg) {
  4. $scope.$broadcast('event-name', { message: msg });
  5. };
  6. });

  7. app.controller("subCtrl", function ($scope) {
  8. $scope.$on('event-name', function (event, args) {
  9. $scope.message = args.message;
  10. console.log($scope.message);
  11. });
  12. });