Understanding difference between $scope and $rootScope

$scope and $rootScope are the core object of AngularJS. $scope is an object instance of a controller. $scope object instance get’s created when ng-controller directive is encountered. It acts as a context for evaluating expressions. Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your angular app.

$rootScope is a parent object of all angular objects created in a web page. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. So all other scopes are children of the $rootScope.

Go here for How to Create Custom Filter

Below code snippet will give you the clear view of $rootScope and $scope:


<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="js/angular.min.js"></script>
    <script>
        var app = angular.module('myapp',[]);
        app.controller('MyCtrler1', function ($scope, $rootScope)
        {
            $scope.message1 = "Hello World!! Im from MyCtrler1 scope";
            $scope.globalValue = "im from rootScope";
        });
        app.controller('MyCtrler2', function ($scope)
        {
            $scope.message2 = "Hello AngularJS !!  Im from MyCtrler2 scope";
        });
    </script>
  </head>
  <body ng-app="myapp" style="border:2px solid blue;padding:10px;">
    rootscope space
  <div ng-controller="MyCtrler1" style="border:2px solid red;margin:10px;padding:10px;">
       {{message1}}<br/>
       {{globalValue}}
  </div>
  <div ng-controller="MyCtrler2" style="border:2px solid green;margin:10px;padding:10px;">
       {{message2}}<br/>
       {{message1}}<br/>
       {{globalValue}}
 </div>
 </body>
</html>

 

Here you can see the $rootScope variable globalValue can be accessible anywhere in the application, where as the $scope variable message1 is not accessible with in MyCtrler2 controller. Because the message1 variable is under scope of MyCtrler1 controller.

Here is the output,

difference-between-scope-and-rootscope

 

Finally, we can say in one line as Every application has one single $rootScope whose lifecycle is the same as the app, every controller can have it's own scope, that is not shared with others.

For best practice and code modularity, try to avoid using $rootScope all the time unless it is necessary.

Like this post !?! Follow poppinsboy on google+ to get more updates.


Leave a Reply

Your email address will not be published.