Tutorial 4 - rootScope in controller

Tutorial 4 - $rootScope in controller

$rootScope is parent of a $scope, with $rootScope we can access data from a Controller to  other Controllers.




  •  How to define a $ rootScope in Javascript?
 <script>  
  myWebApp = angular.module('myWebApp', []);  
  myWebApp.controller("Controller01", function($scope, $rootScope){  
   $rootScope.message = 'Welcome to AngularJS Blog';  
  });  
  myApp.controller("Controller02", function($scope){  
  });  
 </script>  
   
  • How to use it in HTML?
 <body ng-app=" myWebApp ">  
   <div ng-controller="Controller01">  
     <input type="text" ng-model="message"/>  
     {{message}}  
   </div>  
   <div ng-controller="Controller02">  
     <input type="text" ng-model="message"/>  
     {{message}}  
   </div>  
 </body>  
   
  • You will know more about $rootScope after you run following single page
 <!DOCTYPE html>  
 <html>  
 <script>  
 myWebApp = angular.module('myWebApp', []);  
 myWebApp.controller("Controller01", function($scope, $rootScope){  
   $rootScope.message = 'Welcome to AngularJS Blog';  
 });  
 myApp.controller("Controller02", function($scope){  
 });  
 </script>  
 <body ng-app=" myWebApp ">  
   <div ng-controller="Controller01">  
     <input type="text" ng-model="message"/>  
     {{message}}  
   </div>  
   <div ng-controller="Controller02">  
     <input type="text" ng-model="message"/>  
     {{message}}  
   </div>  
 </body>  
 </html>  
   



2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This example has a small mistake at 2nd controller
    myApp.controller("Controller02", function($scope){
    });
    should be
    myWebApp.controller("Controller02", function($scope,$rootScope){
    });

    ReplyDelete

Popular Posts