简体   繁体   中英

Why would you ever use the $rootScope?

Ok so I was reading here

basically when I have this

MyApp = MyApp || {};

MyApp.settings = {
    isFooEnabled: false
}

if I use the rootscope and want to check if isFooEnabled I have to inject the rootScope into whatever object I want to do the check.

How does that make sense?

What is the advantage of using $rootScope.isFooEnabled over using straight standard javascript MyApp.isFooEnabled ?

what is better for what?

when should I use one over the other?

The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.

The rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently.

NOTE:

  1. When you use ng-model with $rootScope objects then AngularJS updates those objects under a specific $scope of a controller but not at global level $rootScope.

  2. The $rootScope shouldn't be used to share variables when we have things like services and factories.

Finally, Angular FAQ says this at the bottom of the page: "Conversely, don't create a service whose only purpose in life is to store and return bits of data." See from here .

Actually, I would argue that you shouldn't use $rootScope in this case, you should create a separate service (or factory) that stores your settings, however, the usage and reasons are the same.

For simply storing values, the primary reason is consistency. Modules and dependency injection are a big part of angular to ensure you write testable code, and these all use dependency injection so that unit tests can be written easily (dependencies can be mocked). Whilst there are not many obvious gains from injecting a simple object, it's consistent with the way more complex code is accessed, and there is a lot to be said for that. On a similar note, if you were to upgrade your settings object to fetch data from the server (eg for environment specific settings), you might want to start unit testing that functionality, which you can't really do properly without modularising it.

There is also the (frankly weak) namespacing argument - what if another library you import uses window.MyApp ?

TL;DR: It's a strongly recommended best-practice. It might seem a bit clunky now, but you'll benefit from doing it in the long run.

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