Understanding root scope and scope in AngularJS
Posted By : Ravi Verma | 31-Mar-2015
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!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.