The response provided by JosselinTD is accurate. When an event is broadcasted on the $rootScope, you can simply listen on your controller's $scope since a broadcast triggers on all scopes nested below the scope where the event originated, with all other scopes residing beneath the $rootScope.
If direct listening is not possible, for instance, when capturing an emitted event (via $emit) that does not reach your $scope, you have the option to listen on the $rootScope. However, it is crucial to ensure proper cleanup of the listener when the controller's scope is destroyed:
var removeListener = $rootScope.$on('yourEvent', function(event) {
// implement desired actions here..
});
// Remove the listener from $rootScope upon scope destruction
// This prevents any unwanted references...
$scope.$on('$destroy', removeListener);
The $on method yields a function for removing the created listener. AngularJS automatically triggers the $destroy event on your $scope when a controller is being disposed of (e.g., view replacement).
When handling non-angular events in a controller, remember to utilize
$scope.$on('$destroy', function() {
//TODO: Invoke cleanup function to remove event listener
});
It may also be beneficial to refer to socket io listener removal guidance on Stack Overflow.
Additionally, if monitoring external events outside the AngularJS context (e.g., DOM or socket.io events), wrap them within a $scope.$apply to notify AngularJS of any changes introduced by the event listener.
socket.on('someSocketEvent', function(data) {
$scope.$apply(function() {
$scope.dataFromSocket = data;
});
});