The framework provides another way to communicate between components by the means of a scope, however, without sharing it. To achieve this, we can use a function called
$broadcast
.
When invoked, this function dispatches an event to all of its registered child scopes.In order to receive and handle the desired broadcast,
$scope
needs to call the
$on
function, thus informing you of the events you want to receive and also the functions that will be handling it.
For implementing, we are going to send the broadcast through the
$rootScope
object, which means that the broadcast will affect the entire application.
In the following code, we created a service called TickGenerator. It informs the current date every second, thus sending a broadcast to all of its children
services.js
snippet
parking.factory("tickGenerator", function($rootScope, $timeout) {
var _tickTimeout;
var _start = function() {
_tick();
};
var _tick = function() {
$rootScope.$broadcast("TICK", new Date());
_tickTimeout = $timeout(_tick, 1000);
};
var _stop = function() {
$timeout.cancel(_tickTimeout);
};
var _listenToStop = function() {
$rootScope.$on("STOP_TICK", function(event, data) {
_stop();
});
};
_listenToStop();
return {
start: _start,
stop: _stop
};
});
Start
tickGenerator using the run function of the module API, as shown in the following code snippet of the
app.js file:
app.js
parking.run(function (tickGenerator) {
tickGenerator.start();
});
To receive the current date, freshly updated, we just need to call the $on function of any $scope object, as shown in the following code snippet of the
parking.html file:
Consider the following code snippet in the controllers.js file:
snippet
parking.controller("parkingCtrl", function($scope) {
var listenToTick = function() {
$scope.$on('TICK', function(event, tick) {
$scope.tick = tick;
});
};
listenToTick();
});
After the
listenToTick function is called, the controller's $scope object will start to receive a broadcast notification every 1000 ms, executing the desired function. To stop the tick, we need to send a broadcast in the other direction in order to make it arrive at
$rootScope
. This can be done by means of the
$emit
function, shown as follows in the
parking.html file:
{{tick | date:"hh:mm"}}
<button ng-click="stopTicking()">Stop</button>
Consider the following code snippet in the controllers.js file:
snippet
parking.controller("parkingCtrl", function($scope) {
$scope.stopTicking = function() {
$scope.$emit("STOP_TICK");
};
var listenToTick = function() {
$scope.$on('TICK', function(event, tick) {
$scope.tick = tick;
});
};
listenToTick();
});
Note:-
Note
Depending on the size of the application, the broadcast through $rootScope may become too heavy due to the number of objects listening to the same event. There are a number of libraries that implement the publish and subscribe pattern in JavaScript. Of them, the most famous is AmplifyJS, but there are others such as RadioJS, ArbiterJS, and PubSubJS.