[Solved-4 Solutions] Working with $scope.$emit and $scope.$on - javascript Tutorial
Problem:
How $scope.$emit and $scope.$on works ?
Solution 1:
function firstCtrl($scope)
{
$scope.$emit('someEvent', [1, 2, 3]);
}
function secondCtrl($scope)
{
$scope.$on('someEvent', function (mass)
{
console.log(mass);
});
}
Read Also
Solution 2:
If scope of firstCtrl
is parent of the secondCtrl
scope, your code should work by replacing $emit
by $broadcast
in firstCtrl
:
function firstCtrl($scope)
{
$scope.$broadcast('someEvent', [1,2,3]);
}
function secondCtrl($scope)
{
$scope.$on('someEvent', function(event, mass) { console.log(mass); });
}
In case there is no parent-child relation between your scopes you can inject $rootScope
into the controller and broadcast the event to all child scopes (i.e. also secondCtrl
).
function firstCtrl($rootScope)
{
$rootScope.$broadcast('someEvent', [1,2,3]);
}
Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit
. If scope of firstCtrl
is parent of the secondCtrl
scope:
function firstCtrl($scope)
{
$scope.$on('someEvent', function(event, data) { console.log(data); });
}
function secondCtrl($scope)
{
$scope.$emit('someEvent', [1,2,3]);
}
Solution 3:
var unbindEventHandler = $rootScope.$on('myEvent', myHandler);
$scope.$on('$destroy', function ()
{
unbindEventHandler();
});
Solution 4:
Case 1:
$rootScope.$broadcast:-

Learn JavaScript - JavaScript tutorial - $scope.$broadcast- JavaScript examples - JavaScript programs
$rootScope.$broadcast('myEvent',$scope.data);
$rootScope.$on('myEvent', function(event, data) {}
$rootScope
listener are not destroyed automatically. You need to destroy it using $destroy
. It is better to use $scope.$on
as listeners on $scope
are destroyed automatically i.e. as soon as $scope
is destroyed.
$scope.$on('myEvent', function(event, data) {}
Or,
var customeEventListener = $rootScope.$on('myEvent', function(event, data)
{
}
$scope.$on('$destroy', function()
{
customeEventListener();
});

Learn JavaScript - JavaScript tutorial - $scope.$on- JavaScript examples - JavaScript programs
Case 2:
$rootScope.$emit:
Read Also
$rootScope.$emit('myEvent',$scope.data);
$rootScope.$on('myEvent', function(event, data) {}//$scope.$on not works

Learn JavaScript - JavaScript tutorial - $scope.$emit- JavaScript examples - JavaScript programs