Search code examples
javascriptangularjsrootscopeangularjs-rootscope

Difference between $rootScope and $rootScope.$root


Is there any difference between $rootScope and $rootScope.$root?

What is the difference between

$rootScope.global.flag = true and $rootScope.$root.global.flag = true

Do both of them access the same variable in rootscope?

If so, is there any particular situation where we have to use either of them?


Solution

  • All scopes in Angular are instances of the same prototype. As such, the global service $rootScope is the same type of object created for directives and passed to the link function as $scope, or for controllers.

    The property $root is part of that prototype and available on all scopes.

    The $rootScope is the first scope created by Angular. All scopes are created by using the $new method from an existing scope. So $rootScope is a special case because it's created before angular.run() is executed on modules.

    When you check the value of $scope.$root it references the same instance that is provided by the root scope service for $rootScope.

    Therefore;

    console.log($rootScope === $scope.$root); // will print true
    

    Or as in your example;

    console.log($rootScope === $rootScope.$root); // will also print true
    

    So yes, the variables in the root scope are the same no matter how you reference the root scope.

    console.log($rootScope.global.flag); // prints true
    console.log($scope.$root.global.flag); // prints true
    console.log($rootScope.$root.global.flag); // prints true
    

    You can also explicitly access the root scope in template expressions like this.

    <div>{{$root.someValue}}</div>
    

    There are other properties like $parent that let you walk up the chain of scopes, but $parent will be null for isolated scopes (since it has no parent).