之间有什么$范围。$根$ rootScope区别? [英] What is the difference between $scope.$root and $rootScope?
问题描述
我控制器看到$范围有$根,这是什么?它是如何从$ 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?
推荐答案
$ rootScope
VAR指向所有范围的父母和随处注入。所有其他的范围是的 $ rootScope
的孩子。它们通过的 $新的
方法创建的 $ rootScope
因此,每一个范围继承的 $ rootScope
。
$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
.
在范围
构造<定义角源href=\"https://github.com/angular/angular.js/blob/d7ecab775ceefcd55a23780d005ce1c39cd8651b/src/ng/rootScope.js#L130\">there是行:
function Scope() {
this.$id = nextUid();
...
this['this'] = this.$root = this;
...
看来 $根
VAR仅仅是的占位符该
创建的第一个范围 - $ rootScope
。
It seems the $root
var is just a placeholder for this
of the first scope created - $rootScope
.
接下来是<一个href=\"https://github.com/angular/angular.js/blob/d7ecab775ceefcd55a23780d005ce1c39cd8651b/src/ng/rootScope.js#L180\">this一块在 $新的
方法code 的:
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;
所以 $ rootScope
的每一个范畴孩子的 $根
VAR是 $ rootScope
。而这些孩子的所有孩子会得到同样的参考 $ rootScope
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
在我看来,这是更好地通过依赖注入使用 $ rootScope
,因为它是一个明确的和整体更为常用参照 $ 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
这篇关于之间有什么$范围。$根$ rootScope区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!