AngularJS Using angular event system


Example

$scope.$emit

Using $scope.$emit will fire an event name upwards through the scope hierarchy and notify to the $scope.The event life cycle starts at the scope on which $emit was called.

Working wireframe :

enter image description here

$scope.$broadcast

Using $scope.$broadcast will fire an event down the $scope. We can listen of these events using $scope.$on

Working wireframe :

enter image description here

Syntax :

// firing an event upwards
$scope.$emit('myCustomEvent', 'Data to send');

// firing an event downwards
$scope.$broadcast('myCustomEvent', {
  someProp: 'some value'
});

// listen for the event in the relevant $scope
$scope.$on('myCustomEvent', function (event, data) {
  console.log(data); // 'Data from the event'
});

Instead of $scope you can use $rootScope, in that case your event will be available in all the controllers regardless of that controllers scope

Clean registered event in AngularJS

The reason to clean the registered events because even the controller has been destroyed the handling of registered event are still alive. So the code will run as unexpected for sure.

// firing an event upwards
$rootScope.$emit('myEvent', 'Data to send');

// listening an event
var listenerEventHandler = $rootScope.$on('myEvent', function(){
    //handle code
});

$scope.$on('$destroy', function() {
    listenerEventHandler();
});