Rootscope in angular JS

By
$rootscope in angualr
In this article i explain what is rootscope in angular js & how its different from normal scope. First thing we have notice is every application has a single rootscope and we can use this entirely in application. Simple means is $rootScope is available for all controller but the $scope only within the controller. In another way we can say that $scope is an object that is accessible to current controller & $rootScope is also an object which is accessible from anywhere in the application .
For example if you make any variable global then it will accessible from everywhere & in case of local variable only local accessible are present same like $scope & $rootScope. $scope is created with ng-controller while $rootscope is created with ng-app. Here we give an example of the $rootScope. you have to also notice that controller's color variable does not overwrite the rootScope's color value in below example.

rootScope in Angualr JS

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
  <div>I am not in any controller </div>
  <p>rootScope Properties Call :- {{color}}</p>
  <div ng-controller="myCtrl">
    <fieldset>
      <legend>
        I am in Controller
      </legend>
      <p>Controller Properties Call :- {{color}}</p>
      <p>rootScope Properties Call :-  {{$parent.color}}</p>
   </fieldset>
  </div>
  <div>Again i am not in any Controller </div>
  <p>rootController property color is called :- {{color}}</p>
 <script>
   var app = angular.module('myApp', []);
   app.run(function($rootScope) {
     $rootScope.color = 'blue';
   });
   app.controller('myCtrl', function($scope) {
     $scope.color = "red";
   });
 </script>
</body>
</html>

output of rootScope in Angualr JS

I am not in any controller
rootScope Properties Call :- blue
I am in Controller
Controller Properties Call :- red
rootScope Properties Call :- blue
Again i am not in any Controller
rootController property color is called :- blue

0 comments:

Post a Comment