简体   繁体   English

何时在Angularjs上使用$ rootScope?

[英]When to use $rootScope on Angularjs?

如果在控制器之间共享数据的正确方法是使用工厂/服务,$ rootScope的目的是什么?

$rootScope exists, but it can be used for evil $rootScope存在,但它可以用于邪恶

Scopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Angular中的作用域形成一个层次结构,原型继承自树顶部的根作用域。 Usually this can be ignored, since most views have a controller, and therefore a scope, of their own. 通常这可以忽略,因为大多数视图都有自己的控制器,因此也有范围。

Occasionally there are pieces of data that you want to make global to the whole app. 有时,您希望为整个应用程序提供全局数据。 For these, you can inject $rootScope and set values on it like any other scope. 对于这些,您可以像任何其他范围一样注入$rootScope并在其上设置值。 Since the scopes inherit from the root scope, these values will be available to the expressions attached to directives like ng-show just like values on your local $scope . 由于范围继承自根范围,因此这些值可用于附加到ng-show等指令的表达式,就像本地$scope上的值一样。

Of course, global state sucks and you should use $rootScope sparingly , like you would (hopefully) use with global variables in any language. 当然,全局状态很糟糕, 你应该谨慎使用$rootScope ,就像你希望用任何语言的全局变量一样。 In particular, don't use it for code, only data. 特别是,不要将它用于代码,只用于数据。 If you're tempted to put a function on $rootScope , it's almost always better to put it in a service that can be injected where it's needed, and more easily tested. 如果您想在$rootScope上添加一个函数,那么将它放在一个可以在需要的地方注入的服务并且更容易测试几乎总是更好。

Conversely, don't create a service whose only purpose in life is to store and return bits of data. 相反,不要创建一个服务,其唯一目的是存储和返回数据位。

-- AngularJS FAQ - AngularJS常见问题解答

As per my understanding. 据我所知。 you can use $rootScope in multiple places . 你可以在多个地方使用$ rootScope。

  • global settings defined in factory and then in view you can update as per your condition. 在工厂中定义的全局设置,然后在视图中,您可以根据您的条件进行更新。 fx layout manipulation fx布局操作
  • you can assigned $state on run. 你可以在运行中分配$ state。
  • you can handle error ($rootScope.$on(...) 你可以处理错误($ rootScope。$ on on(...)

I hope this will help. 我希望这将有所帮助。

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM