Angular JS - What is $rootScope?

  1. $Scope is a javascript object associated to controller.
  2. Controller constructor function is responsible for setting the properties and methods to the $scope object.
  3. Methods and properties are created in the $Scope object are only accessed from the controller(Html view).
  4. $rootScope  is a javascript object which is parent of all $scope object.
  5. All other scopes are descendant scopes of the root scope.
  6. $rootScope object could communicate across the scopes.



<body ng-app="sampleApp">
    <div ng-controller="AppCtrl1" style="border:1px solid blue; padding:5px">
     Hello {{msg}}!
     <br />
     Hello {{name}}! (rootScope)
    </div>
    <br />
    <div ng-controller="AppCtrl2" style="border:1px solid green; padding:5px">
     Hello {{msg}}!
     <br />
     Hey {{myName}}!
     <br />
     Hi {{name}}! (rootScope)
    </div>
    <script src="angular.js"></script>

     <script>
     var app = angular.module('sampleApp', []);
     app.controller('AppCtrl1', function ($scope, $rootScope) {
     $scope.msg = 'World';
     $rootScope.name = 'Angular JS';
     });
     app.controller('AppCtrl2', function ($scope, $rootScope) {
     $scope.msg = 'Astute JS';
     $scope.myName = $rootScope.name;
     });
     </script>


  

No comments

Powered by Blogger.