Newsletter

Understanding of Angular’s $rootScope and $scope?

AngularJs » on Aug 4, 2016 { 4 Comments } By Sivateja

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

Here it is..
rootScope-vs-scope

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 .::

Java4s_Author
- Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

4 Responses to “Understanding of Angular’s $rootScope and $scope?”
  1. himabindu says:

    Please upload the complete topics of AngularJs.Your way of teaching is nice.

  2. chetan says:

    Please Share ws and Angular js more tutorials

  3. sambit says:

    Please upload more example on angular js topic .

  4. shubham kala says:

    Please provide more learning stuff about angular….

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2018 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.