我在 Controller 中看到 $scope 有 $root,这是什么?它与可以在 Controller 中注入(inject)的 $rootScope 有何不同?
最佳答案
$rootScope
var 指向所有范围的父级并且可以在任何地方注入(inject)。所有其他范围都是 $rootScope
的子级。它们是通过 $rootScope
的 $new
方法创建的,因此每个作用域都继承自 $rootScope
。
在 Scope
构造函数定义中的 Angular 源中 there is a line :
function Scope() {
this.$id = nextUid();
...
this['this'] = this.$root = this;
...
似乎 $root
var 只是第一个创建范围的 this
的占位符 - $rootScope
。
接下来是this piece of code在 $new
方法中:
$new: function(isolate) {
...
if (isolate) {
child = new Scope();
child.$root = this.$root;
...
return child;
因此 $rootScope
的每个作用域子级的 $root
var 都是对 $rootScope
的引用。这些 child 的所有 child 都将获得对 $rootScope
在我看来,通过依赖注入(inject)使用 $rootScope
更好,因为它是一种明确且总体上更常用的引用 $rootScope
的方式/p>
关于javascript - $scope.$root 和 $rootScope 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216441/