When to use $ rootScope on Angularjs?

If the factory / service uses the correct way to exchange data between controllers, what is the purpose of $ rootScope?

+5
source share
2 answers

$rootScope exists, but it can be used for evil

The regions in Angular form a hierarchy that inherits from the root region at the top of the tree. This can usually be ignored, since most views have a controller and therefore scope.

Sometimes there are pieces of data that you want to make global for the entire application. To do this, you can enter $rootScope and set values ​​for it, as in any other area. Because areas inherited from the root area, these values ​​will be available to expressions attached to directives like ng-show , just like the values ​​on your local $scope .

Of course, the global state sucks and you should use $rootScope sparingly , as you (hopefully) use with global variables in any language. In particular, do not use it for code, but only data. If you are tempted to put a function on $rootScope , it is almost always better to put it in a service that can be inserted where you need it and more easily tested.

Conversely, do not create a service whose sole purpose is to store and return data bits.

- AngularJS Frequently Asked Questions

+6
source

In accordance with my understanding. you can use $ rootScope in several places.

  • global settings defined in the factory, and then you can update them according to your condition. Manage fx layouts
  • you can assign $ state at startup.
  • you can handle the error ($ rootScope. $ on (...)

Hope this helps.

thanks

+3
source

Source: https://habr.com/ru/post/1244074/


All Articles