简体   繁体   中英

When to use $rootScope on Angularjs?

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

$rootScope exists, but it can be used for evil

Scopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. 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. 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 .

Of course, global state sucks and you should use $rootScope sparingly , like you would (hopefully) use with global variables in any language. 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.

Conversely, don't create a service whose only purpose in life is to store and return bits of data.

-- AngularJS FAQ

As per my understanding. you can use $rootScope in multiple places .

  • global settings defined in factory and then in view you can update as per your condition. fx layout manipulation
  • you can assigned $state on run.
  • you can handle error ($rootScope.$on(...)

I hope this will help.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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