Newsletter |
Understanding of Angular’s $rootScope and $scope?
In this article I will describe the relation between Angular’s $rootScope and $scope and how they will work.
As I have explained in AngularJS Controller Example, $scope will work as a mediator between our view and controller for carrying the data in between them. One important point we need to remember here is, each controller will have one $scope object. But every Angular application can have only one $rootScope. The formula is very simple.
‘N’ no. of controllers in application = ‘N’ no. of $scope objects
One Angular Application = 1 $rootScope
Let me explain you with a simple example.
<!DOCTYPE html> <html> <head> <title>Angulars $scope & $rootScope - Java4s.com</title> </head> <body ng-app="myApp"> rootScope color: {{color}} <div ng-controller="java4sCtrl"> scope color (from controller): {{color}} </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script> var app = angular.module('myApp', []); app.controller('java4sCtrl', function($scope, $rootScope) { $scope.color = "red"; $rootScope.color = 'green'; }); </script> </body> </html>
Output
rootScope’s color: green
scope’s color (from controller): red
Explanation
Have you observed, controller’s color variable does not overwrite the rootScope’s color value. Each scope has their own spaces, so there is no problem of overriding. Very important point here is, rootScope’s content can be accessible across all the controllers (I have indicated this in the image). That’s it friends, generally $rootScope will be useful if we would like to achieve the communication between controllers. I will explain more about it in the upcoming article.
::. About the Author .:: | ||
Please upload the complete topics of AngularJs.Your way of teaching is nice.
Please Share ws and Angular js more tutorials
Please upload more example on angular js topic .
Please provide more learning stuff about angular….