What is the difference between $ scope. $ Root and $ rootScope?

I see in the controllers that $ scope has $ root, what is it? How is it different from the $ rootScope that can be entered into the controller?

+35
javascript angularjs angularjs-scope
Mar 06 '14 at 6:10
source share
2 answers

$rootScope var, which points to the parent of all fields and can be entered everywhere. All other areas are children of $rootScope . They are created using the $new $rootScope , so each area is inherited from $rootScope .

There is a line in the angular source in the definition of the Scope constructor:

  function Scope() { this.$id = nextUid(); ... this['this'] = this.$root = this; ... 

It seems that $root var is just a placeholder for this first created area - $rootScope .

Further this code fragment in the $new method:

  $new: function(isolate) { ... if (isolate) { child = new Scope(); child.$root = this.$root; ... return child; 

Thus, $root var of each child of the $rootScope sphere is a reference to $rootScope . And all the children of these children will receive the same link to $rootScope

In my opinion, it is better to use $rootScope through dependency injection, because this is an explicit and common more commonly used way to access $rootScope

+61
Mar 06 '14 at 7:31
source share

As mentioned earlier, $scope.$root contains a link to $rootScope .

Unfortunately, there is a difference between using $scope.$root and using $rootScope :

Thus, you may have a situation where $scope.$root is null . Better use $rootScope instead ...

+23
Dec 15 '14 at 2:06
source share



All Articles