Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - What is the difference between $scope.$root and $rootScope?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$rootScope var which points to the parent of all the scopes and can be injected everywhere. All other scopes are children of the $rootScope. They are created via the $new method of the $rootScope thus every scope inherits from the $rootScope.

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

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

It seems the $root var is just a placeholder for this of the first scope created - $rootScope.

Next there is this piece of code in the $new method:

  $new: function(isolate) {
      ...

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

So the $root var of every scope child of $rootScope is a reference to $rootScope. And all the children of those children will get the same reference to $rootScope

In my opinion it is better to use the $rootScope via dependency injection because it is an explicit and overall more frequently used way of referring to the $rootScope


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...