Thursday 24 August 2017

Passing value one controller to another controller using angularjs



By using $rootScope we can able to pass the date one controller to another

This is HTML code


<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-app="app">
      <div ng-controller="myController1">
        <input type="text" ng-model="controller1Data" ng-change="change()">
        <br/>
        myController1 data:
        {{data}}
      </div>
       <div ng-controller="myController2">
        myController1 data:
        {{data}}
      </div>
    </div>
  </body>

</html>

This is Angularjs Code


  var app=angular.module('app',[]);

//This is your Controller 1

  app.controller('myController1',function($scope,$rootScope){
    $scope.controller1Data='please change textbox value';
    $scope.change=function(){
    $rootScope.data=$scope.controller1Data;
  }
 });

//This is your Controller 2

  app.controller('myController2',function($scope,$rootScope){

     $rootScope.data=$scope.controller1Data;

   });



Follow the bellow plunker https://plnkr.co/edit/AZ48AaflPgCdARLfsita?p=preview

Explanation :
//Create the module
          var app=angular.module('app',[]);
//Create the Controller1 and inject the $scope & $rootScope
          app.controller('myController1',function($scope,$rootScope){
//Assign the data to $scope.controller1Data 
    $scope.controller1Data='please change textbox value';
//ng-change function when change the data in textbox
    $scope.change=function(){
//Assign controller1 data to data
//this is used to pass the data to Controller2
    $rootScope.data=$scope.controller1Data;
  }
 });


//Create the Controller1 and inject the $scope & $rootScope

app.controller('myController2',function($scope,$rootScope){

//Accessing Controller1 Data to Controller2
     $rootScope.data=$scope.controller1Data;

   });


      The above Example we are using '$rootScope'
         
$rootScope is Global scope in Application, We can accessing data to Whole application,means any controller.

No comments:

Post a Comment