Rootscope in angular JS | Code By Topic

Rootscope in angular JS

$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>
<script src=""></script>
<body ng-app="myApp">
  <div>I am not in any controller </div>
  <p>rootScope Properties Call :- {{color}}</p>
  <div ng-controller="myCtrl">
        I am in Controller
      <p>Controller Properties Call :- {{color}}</p>
      <p>rootScope Properties Call :-  {{$parent.color}}</p>
  <div>Again i am not in any Controller </div>
  <p>rootController property color is called :- {{color}}</p>
   var app = angular.module('myApp', []);$rootScope) {
     $rootScope.color = 'blue';
   app.controller('myCtrl', function($scope) {
     $scope.color = "red";

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


Post a Comment