Difference between $scope and $rootScope

JavascriptAngularjs

Javascript Problem Overview


Can anyone explain the difference between $scope and $rootScope?

I think

$scope:

>We can get ng-model properties in particular controller from the particular page by using this.


$rootScope

>We can get all ng-model properties in any controller from any page by using this.


Is this correct? Or anything else?

Javascript Solutions


Solution 1 - Javascript

"$rootScope” is a parent object of all “$scope” angular objects created in a web page.

enter image description here

$scope is created with ng-controller while $rootscope is created with ng-app.

enter image description here

Solution 2 - Javascript

The main difference is the availability of the property assigned with the object. A property assigned with $scope cannot be used outside the controller in which it is defined whereas a property assigned with $rootScope can be used anywhere.

Example: If in the example below you replace $rootScope with $scope the department property will not be populated from the first controller in the second one

angular.module('example', [])
  .controller('GreetController', ['$scope', '$rootScope',
    function($scope, $rootScope) {
      $scope.name = 'World';
      $rootScope.department = 'Angular';
    }
  ])
  .controller('ListController', ['$scope',
    function($scope) {
      $scope.names = ['Igor', 'Misko', 'Vojta'];
    }
  ]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="example">
  <div class="show-scope-demo">
    <div ng-controller="GreetController">
      Hello {{name}}!
    </div>
    <div ng-controller="ListController">
      <ol>
        <li ng-repeat="name in names">{{name}} from {{department}}</li>
      </ol>
    </div>
  </div>
</body>

Solution 3 - Javascript

According to Angular's Developer's Guide to Scopes:

> Each Angular application has exactly one root scope, but may have several child scopes. The application can have multiple scopes, because some directives create new child scopes (refer to directive documentation to see which directives create new scopes). When new scopes are created, they are added as children of their parent scope. This creates a tree structure which parallels the DOM where they're attached. > > Both controllers and directives have reference to the scope, but not to each other. This arrangement isolates the controller from the directive as well as from DOM. This is an important point since it makes the controllers view agnostic, which greatly improves the testing story of the applications.

Solution 4 - Javascript

$rootScope is available globally, no matter what controller you are in, whereas $scope is only available to the current controller and it's children.

Solution 5 - Javascript

In other way we can look at this; $rootScope is global while $scope is local. When Controller is assigned to a page, so a $scope variable can be use here because it binds to this controller. But when we want to share its value across to other controllers or services, then $rootScope is being used (**there are alternative ways, we can share values across but in this case we want to use $rootScope).

Your second question about how you define those two words are correct.

Lastly a bit off track, please use $rootScope with care. Similar to the way you use global variables, can be a pain to debug and you may accidentally change the global variable somewhere inside a timer or something which makes your reading incorrect.

Solution 6 - Javascript

Every application has atleast one single rootScope and its lifecycle is the same as the app and every controller can have it's own scope, that is not shared with others.

Have a look at this article :

https://github.com/angular/angular.js/wiki/Understanding-Scopes

Solution 7 - Javascript

I recommend you read the official in-depth Angular documentation for scopes. Start at the section 'Scope Hierarchies':

https://docs.angularjs.org/guide/scope

Essentially, $rootScope and $scope both identify specific parts of the DOM within which

  • Angular operations are carried out
  • variables declared as part of either the $rootScope or $scope are available

Anything that belongs to the $rootScope is available globally across your Angular app, whereas anything that belongs to a $scope is available within the part of the DOM to which that scope applies.

The $rootScope is applied to the DOM element that is the root element for the Angular app (hence the name $rootScope). When you add the ng-app directive to an element of the DOM, this becomes the root element of the DOM within which $rootScope is available. In other words, properties etc of $rootScope will be available throughout your entire Angular application.

An Angular $scope (and all of it's variables and operations) is available to a particular subset of the DOM within your application. Specifically, the $scope for any particular controller is available to the part of the DOM to which that particular controller has been applied (using the ng-controller directive). Note though that certain directives e.g. ng-repeat, when applied within a part of the DOM where the controller has been applied, can create child scopes of the main scope - within the same controller - a controller doesn't necessarily contain only one scope.

If you look at the generated HTML when you run your Angular app, you can easily see which DOM elements 'contain' a scope, as Angular adds the class ng-scope on any element to which a scope has been applied (including the root element of the app, which has the $rootScope).

By the way, the '$' sign at the start of $scope and $rootScope is simply an identifier in Angular for stuff that's reserved by Angular.

Note that using $rootScope for sharing variables etc. between modules and controllers isn't generally considered best practice. JavaScript developers talk about avoiding 'pollution' of the global scope by sharing variables there, since there may be clashes later on if a variable of the same name is used somewhere else, without the developer realising it's already declared on the $rootScope. The importance of this increases with the size of the application and the team that's developing it. Ideally the $rootScope will only contain constants or static variables, that are intended to be consistent at all times across the app. A better way of sharing stuff across modules may be to use services and factories, which is a another topic!

Solution 8 - Javascript

Both are Java script objects and the difference is illustrated by diagram as below.

enter image description here

NTB:
First angular application try to find the property of any model or function in $scope , if it doesn't found the property in $scope , then it search in parent scope in upper hierarchy. If the property is still not found in upper hierarchy then angular tries to resolve in $rootscope.

Solution 9 - Javascript

New styles, like John Papa's AngularJS Styleguide, are suggesting that we shouldn't be using $scope to save current page's properties at all. Instead we should use the controllerAs with vm approach where the view binds to the controller object itself. Then use a capture variable for this when using the controllerAs syntax. Choose a consistent variable name such as vm, which stands for ViewModel.

You will still need the $scope for its watching capabilities though.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3484362View Question on Stackoverflow
Solution 1 - JavascriptAayushi JainView Answer on Stackoverflow
Solution 2 - JavascriptAli SadiqView Answer on Stackoverflow
Solution 3 - JavascriptGary StaffordView Answer on Stackoverflow
Solution 4 - JavascriptTomView Answer on Stackoverflow
Solution 5 - JavascriptrogerView Answer on Stackoverflow
Solution 6 - JavascriptUser_allowedView Answer on Stackoverflow
Solution 7 - JavascriptChris HalcrowView Answer on Stackoverflow
Solution 8 - JavascriptWaqas AhmedView Answer on Stackoverflow
Solution 9 - JavascriptStanView Answer on Stackoverflow