These events can be used to communicate between 2 or more controllers.
$emit
dispatches an event upwards through the scope hierarchy, while $broadcast
dispatches an event downwards to all child scopes.This has been beautifully explained here.
There can be basically two types of scenario while communicating among controllers:
$scope
in such scenarios)$rootScope
in such scenarios)eg: For any ecommerce website, suppose we have ProductListController
(which controls the product listing page when any product brand is clicked ) and CartController
(to manage cart items) . Now, when we click on Add to Cart button , it has to be informed to CartController
as well, so that it can reflect new cart item count/details in the navigation bar of the website. This can be achieved using $rootScope
.
With $scope.$emit
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller("FirstController", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
});
});
app.controller("SecondController", function ($scope) {
$scope.handleClick = function (msg) {
$scope.$emit('eventName', {message: msg});
};
});
</script>
</head>
<body ng-app="app">
<div ng-controller="FirstController" style="border:2px ;padding:5px;">
<h1>Parent Controller</h1>
<p>Emit Message : {{message}}</p>
<br />
<div ng-controller="SecondController" style="border:2px;padding:5px;">
<h1>Child Controller</h1>
<input ng-model="msg">
<button ng-click="handleClick(msg);">Emit</button>
</div>
</div>
</body>
</html>
With $scope.$broadcast
:
<html>
<head>
<title>Broadcasting</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller("FirstController", function ($scope) {
$scope.handleClick = function (msg) {
$scope.$broadcast('eventName', {message: msg});
};
});
app.controller("SecondController", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
});
});
</script>
</head>
<body ng-app="app">
<div ng-controller="FirstController" style="border:2px solid ; padding:5px;">
<h1>Parent Controller</h1>
<input ng-model="msg">
<button ng-click="handleClick(msg);">Broadcast</button>
<br /><br />
<div ng-controller="SecondController" style="border:2px solid ;padding:5px;">
<h1>Child Controller</h1>
<p>Broadcast Message : {{message}}</p>
</div>
</div>
</body>
</html>