Understanding root scope and scope in AngularJS

Posted By : Ravi Verma | 31-Mar-2015
Understanding root scope and scope in AngularJS

Application model is reffered by an object known as Scope, That is the intermidiate between controller and view. Scopes are of hierarchical nature and follow the Document Object Model structure for angular app.

AngularJS has two scope objects: $rootScope and $scope.

$scope

A $scope is an object of java script that communicates with controller and view. Basically, $scope binds DOM element to the view model and functions defined in a controller.

$rootScope

he $rootScope is the parent scope. An app can have only one $rootScope which shares among all the controllers of an app, as it acts like a global variable. All the $scopes are children of the $rootScope.

Create a file "app.js"




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

       //the run function acts as a main method for the angular app.
       app.run(function ($rootScope) {
           $rootScope.websiteName = "oodlestechnologies.com";
           $rootScope.name = "Ravi Verma"
       });

       app.controller("mainController", function ($scope, $rootScope) {
           $scope.name = "Abhimanyu Singh";
           $scope.greeting = "Welcome to " + $rootScope.websiteName ;
       });

       app.controller("subController", function ($scope, $rootScope) {
           $scope. greeting = "Welcome to " + $rootScope.websiteName ;
 
       });
  

Create a file "index.html"

rootScopeController
rootScope: {{websiteName}}
 

rootScope(ng-model): 
welcome from scope: {{greeting}}
welcome from scope(ng-model): 
scope: {{name}}
ScopeController
rootScope: {{websiteName}}
 

rootScope(ng-model): 
welcome from scope: {{greeting}}
name from rootScope: {{name}}
Outside from both the Controller
name from rootScope: {{name}}
site from rootScope: {{websiteName}}

Hope you find it helpful!

Thanks!

About Author

Author Image
Ravi Verma

Ravi is a seasoned technologist with excellent experience in AngularJS , NodeJS and MEAN stack. He has good experience in developing complex UIs for web and mobile applications.

Request for Proposal

Name is required

Comment is required

Sending message..