Open In App

How to establish communication between independent components in AngularJS ?

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

AngularJS is a popular open-source web application framework that allows developers to create dynamic and interactive web applications. One of the key features of AngularJS is its ability to allow independent components to communicate with each other. In this article, we will see the process of establishing communication between independent components in AngularJS, along with understanding the different possible ways to communicate between the independent components with the help of examples.

The following methods can be utilized for establishing communication between components, which are described below:

Using the $rootScope: The $rootScope is a global scope that is accessible by all components in an AngularJS application. You can use the $rootScope to store data or events that need to be shared between components.

Approach 1: In this approach, we have two independent components, i.e., ControllerA and ControllerB. When the user clicks the “Send Data to Component B” button in ControllerA, we use $rootScope.$broadcast() to send the data to ControllerB. Then, in ControllerB, we use $rootScope.$on() to listen for the data and update the view.

Example: In this example, we have used the $rootScope.$broadcast() & $rootScope.$on() that will help to establish communication between independent components.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Establishing communication between
        independent components in AngularJS
    </title>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <h1 style="color:green">
        GeeksForGeeks
    </h1>
    <div ng-controller="ControllerA">
        <h1>Component A</h1>
        <input type="text" 
               ng-model="dataFromA" />
        <button ng-click="sendData()">
            Send Data to Component B          
        </button>
    </div>
  
    <div ng-controller="ControllerB">
        <h1>Component B</h1>
        <p>Data from Component A: {{dataFromA}}</p>
    </div>
  
    <script>
        var app = angular.module('myApp', []);
        app.controller('ControllerA', 
                       function ($scope, $rootScope) {
            $scope.sendData = function () {
                $rootScope.$broadcast('dataFromA', 
                                      $scope.dataFromA);
            }
        });
  
        app.controller('ControllerB', 
                       function ($scope, $rootScope) {
            $rootScope.$on('dataFromA', 
                           function (event, data) {
                $scope.dataFromA = data;
            });
        });
    </script>
</body>
  
</html>


Output:

 

Using AngularJS Service: A Service is a singleton object in AngularJS that can be used to share data or functionality between components.

Approach 2: In this approach, we have two components (myCtrl1 and myCtrl2) that share data through a service (myService). The sharedData object in the service holds the data that needs to be shared between the components. The setSharedDataForComponent1 and setSharedDataForComponent2 methods in the service update the messageFromComponent1 and messageFromComponent2 properties respectively based on the input from the components.

Example: This example describes the communication between the independent components with the help of Services in AngularJS.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Establishing communication between
        independent components in AngularJS
    </title>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <h1 style="color:green">
          GeeksForGeeks
      </h1>
    <div ng-controller="myCtrl1">
        <h2>Component 1</h2>
        <input type="text" 
               ng-model="sharedData.message">
        <p>
           Message from Component 2: 
           {{sharedData.messageFromComponent2}}
          </p>
    </div>
    <div ng-controller="myCtrl2">
        <h2>Component 2</h2>
        <input type="text" 
               ng-model="sharedData.message">
        <p>
              Message from Component 1:
            {{sharedData.messageFromComponent1}}
          </p>
    </div>
  
    <script>
        var app = angular.module('myApp', []);
        app.factory('myService', function () {
            var sharedData = { message: '', 
                               messageFromComponent1: '', 
                               messageFromComponent2: '' };
  
            return {
                getSharedData: function () {
                    return sharedData;
                },
                setSharedDataForComponent1: function (message) {
                    sharedData.messageFromComponent2 = message;
                },
                setSharedDataForComponent2: function (message) {
                    sharedData.messageFromComponent1 = message;
                }
            };
        });
  
        app.controller('myCtrl1', function ($scope, myService) {
            $scope.sharedData = myService.getSharedData();
  
            $scope.$watch('sharedData.message', 
                          function (newValue, oldValue) {
                myService.setSharedDataForComponent2(newValue);
            });
        });
  
        app.controller('myCtrl2', function ($scope, myService) {
            $scope.sharedData = myService.getSharedData();
  
            $scope.$watch('sharedData.message', 
                          function (newValue, oldValue) {
                myService.setSharedDataForComponent1(newValue);
            });
        });
    </script>
</body>
  
</html>


Output:

 

$emit and $on: The $emit method is used to emit an event from a child scope to its parent scope, and the $on method is used to listen to that event.

Approach 3: In this approach, we have two independent components, i.e., Component A and Component B. Component A has an input field and a button. When the button is clicked, the message entered in the input field is emitted using $emit. Component B has a paragraph element that displays the message received from Component A.

Example: This example illustrates the establishment of communication between independent components with the help of the $emit and $on methods.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
        Establishing communication between
        independent components in AngularJS
    </title>
    <script src=
    </script>
</head>
  
<body ng-controller="MainController">
    <h1 style="color:green">
          GeeksForGeeks
      </h1>
    <div>
        <h2>Component A</h2>
        <input type="text" 
               ng-model="message" />
        <button ng-click="sendMessage()">
              Send Message
          </button>
    </div>
  
    <div>
        <h2>Component B</h2>
        <p>{{receivedMessage}}</p>
    </div>
  
    <script>
        var app = angular.module('myApp', []);
        app.controller('MainController',
                       ['$scope', function ($scope) {
            $scope.message = '';
            $scope.sendMessage = function () {
                $scope.$emit('message', $scope.message);
            };
        }]);
  
        app.controller('ComponentBController', 
                       ['$scope', function ($scope) {
            $scope.receivedMessage = '';
            $scope.$on('message', function (event, message) {
                $scope.receivedMessage = message;
            });
        }]);
  
        app.directive('componentB', function () {
            return {
                restrict: 'E',
                controller: 'ComponentBController',
                template: 
          '<div><h2>Component B</h2><p>{{receivedMessage}}</p></div>'
            };
        });
    </script>
    <component-b></component-b>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads