AngularJS: making two separate controllers communicate

AngularJS: making two separate controllers communicate

In AngularJS there's a specific solution to make two separate controllers communicate directly with one another.

In AngularJS there's a specific solution to make two separate controllers communicate directly with one another.

We can use AngularJS events for our purpose:


angular.module('MyApp').controller('FirstCtrl', ['$scope', function($scope) {
    $scope.$on('my-event', function(event, data) {
        console.log(data); // {test: 1}
    });
}]);

angular.module('MyApp').controller('SecondCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {
    $rootScope.$broadcast('my-event', {test: 1});
}]);

Basically, the second controller sends its data through the root scope and the first controller intercepts the event triggered along with the associated data. However, the major benefits of this technique are those related to specific controller's actions.