Share data between controllers in AngularJS

In this tutorial, we will see how to share data between two controller in Angular JS.

 

  1. Global Variable
  2. Services
    1.   <body ng-app="myApp">
      
                      <div ng-controller="AppControllerOne">
                                      <input type="text" ng-model = 'name' />
                                    <button ng-click="testing()">Click</button>
                      </div>
                      <div ng-controller="AppControllerTwo" ng-init="second = 's'">
                                    {{second}}
                      </div>
                       <script>
                                  var app = angular.module('myApp', []);
                                    app.controller('AppControllerOne', function ($rootScope,$scope, myService) {
      
                                                     $scope.name = "Vinodh";
                                                     $scope.testing = function(){
                                                                      myService.setMessage($scope.name);
                                                                      $rootScope.$broadcast("name_upate");
      
                                                      }
      
                                      });
      
                                     app.controller('AppControllerTwo', function ($scope, myService) {
      
                                                                       
      
                                                      $scope.$on("name_upate",function(){
      
                                                      $scope.second = myService.getMessage();
      
                                                      });
      
                                      });
      
                                     
      
                                      app.service('myService', function () {
      
                                                      var message = "";
      
                                                      var serviceObj = {};
      
                                                      serviceObj.setMessage = function (mesg){
      
                                                         this.message= mesg;
      
                                                      };
      
                                                      serviceObj.getMessage = function (){
      
                                                                      return this.message;
      
                                                      };
      
                                                      return serviceObj;
      
                                      });
      
                      </script>
      
        </body>

Leave a Comment

Your email address will not be published. Required fields are marked *