AngularJS: $scope $emit $on examples
Emit : Upwards
$emit
This will dispatch an event upwards through the scope hierarchy.
function parentCtrl($scope){
$scope.$on('myEvent', function(event, data) { console.log(data); });
}
function childCtrl($scope){
$scope.$emit('myEvent', 'my data');
}
Broadcast : Downwards
$broadcast
This will dispatch an event from the parent scope downwards to all child scopes
function parentCtrl($scope)
{
$scope.$broadcast('myEvent', 'my data');
}
function childCtrl($scope)
{
$scope.$on('myEvent', function(event, data) { console.log(data); });
}
Broadcast: No relationship
If there is no parent/child relationships between the two controllers, you can use $rootScope to broadcast the event.
function myCtrl($rootScope)
{
$rootScope.$broadcast('myEvent', 'my data');
}
Further Reading
Some of this content was borrowed from this fantastic stackoverflow post containing AngularJS $scope, $emit, and $on examples.