This post was most recently updated on July 31st, 2024
An AngularJS application has a single $rootScope. All the other $scope objects are child objects.
The properties and methods attached to $rootScope will be available to all the controllers.
The following example demonstrates the $rootScope and $scope object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> </head> <body ng-app="myNgApp"> <h1>AngularJS $rootScope Demo: </h1> <div ng-controller="parentController"> Controller Name: {{controllerName}} <br /> Message: {{message}} <br /> <div style="margin:10px 0 10px 20px;" ng-controller="childController"> Controller Name: {{controllerName}} <br /> Message: {{message}} <br /> </div> </div> <div ng-controller="siblingController"> Controller Name: {{controllerName}} <br /> Message: {{message}} <br /> </div> var ngApp = angular.module('myNgApp', []); ngApp.controller('parentController', function ($scope, $rootScope) { $scope.controllerName = "parentController"; $rootScope.message = "Hello World!"; }); ngApp.controller('childController', function ($scope) { $scope.controllerName = "childController"; }); ngApp.controller('siblingController', function ($scope) { }); </body> </html> |
and the output looks like
1 2 3 4 5 6 7 |
AngularJS $rootScope Demo: Controller Name: parentController Message: Hello World! Controller Name: childController Message: Hello World! Controller Name: Message: Hello World! |
Drop comment if you have any query. 🙂