- AngularJS provides publish subscribe mechanism using using $emit and $broadcast mechanism.
- A published message can be subscribed or listened using $on method.
- In this demo, "We will learn the difference between Emit and broadcast pub-sub mechanism using a real simple example".
- Difference between Emit and Broadcast is the way they propagate or traveled from the source.
- A message publish via $emit propagates upward and travel up to $rootScope.scope.
- A message published via $broadcast propagate downward towards the children scope.
- Below code shows the demonstration of emit and broadcast.When you press emit button the string typed in the input box published as a message and traveled upward and listened by the listener attached in GrandParentController. When you press broad button the string typed in the input box published as a message and traveled downward and listened by the listener attached in ChildController.
<!DOCTYPE html> <html ng-app="myApp"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> <style> .red { color: blue; font-size: 20px; } .green { color: green; font-size: 26px; } </style> </head> <body> <div ng-controller="GrandParentController"> GrandParent : <span ng-bind="grandNameContainer" class="red"></span> <div ng-controller="ParentController"> <input ng-model="studentName" placeholder="Enter Name"> <button ng-click="emitMyName(studentName)"> Emit </button> <button ng-click="broadcastMyName(studentName)"> Broadcast </button> <div ng-controller="ChildController"> Child : <span ng-bind="childNameContainer" class="green"> </span> </div> </div> </div> <script> var myApp = angular.module('myApp', []); myApp.controller("ParentController", function($scope) { $scope.emitMyName = function(studentName) { $scope.$emit("namePublished", { "studentName": studentName }); }; $scope.broadcastMyName = function(studentName) { $scope.$broadcast("namePublished", { "studentName": studentName }); }; }); myApp.controller("ChildController", function($scope) { $scope.$on('namePublished', function(event, args) { console.log(args); $scope.childNameContainer = args.studentName; }); }); myApp.controller("GrandParentController", function($scope) { $scope.$on('namePublished', function(event, args) { console.log(args); $scope.grandNameContainer = args.studentName; }); }); </script> </body> </html>
- output of the demo shows the below embedded JSBIN
link.