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?
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.
$rootScope exists, but it can be used for evilScopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.
$digest(), $rootScope. $apply(). It updates the data binding. It iterates through all the watches and checks any value updated.
What is alternative of rootScope in Angular? In similar way, you can use use the sharedService inside any component & fetch the returing output and used inside your view. That's it. I found this solution as a good alternative of rootScope.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With