$scope.$root 和 $rootScope 有什么区别? [英] What is the difference between $scope.$root and $rootScope?

查看:30
本文介绍了$scope.$root 和 $rootScope 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器中看到 $scope 有 $root,这是什么?与可以注入控制器的 $rootScope 有什么不同?

解决方案

$rootScope var 指向所有作用域的父级,可以在任何地方注入.所有其他范围都是 $rootScope 的子级.它们是通过 $rootScope$new 方法创建的,因此每个作用域都继承自 $rootScope.

Scope 构造函数定义中的角度源有一行 :

 函数作用域() {this.$id = nextUid();...this['this'] = this.$root = this;...

似乎 $root 变量只是创建的第一个范围的 this 的占位符 - $rootScope.

接下来是这段代码$new 方法:

 $new: function(isolate) {...如果(隔离){孩子 = 新范围();child.$root = this.$root;...返回孩子;

所以 $rootScope 的每个子作用域的 $root 变量都是对 $rootScope 的引用.并且这些孩子的所有孩子都将获得对 $rootScope

的相同引用

在我看来,通过依赖注入使用 $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 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

这篇关于$scope.$root 和 $rootScope 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆