0

I was using AngularJS a lot and I often read "don't over use $rootScope, it's bad practice".

Then, when React came up with the Flux pattern there was one central place for all data, which remembered me on $rootScope.

If I would use the $rootScope object as the single source of truth, what would be the difference to other approaches like Flux?

I mean, you could also just use $rootScope to organize the data, like for example $rootScope.loggedInUser, $rootScope.userList and so on. And you could make a service where all $rootScope changes will be made, so that you know where to look, when something happens.

Would be nice if someone could explain why this wouldn't be a good idea (or telling me, that it's basically okay. Im open) :)

Edit: Related question doesn't answer the question about the difference of $rootScope and Flux pattern.

EscapeNetscape
  • 2,892
  • 1
  • 33
  • 32
  • Well, instead of assigning lots of properties to the `$rootScope` you are better of storing the data in a `service`. Then inject that service instead of injecting the `$rootScope`. – Red Jul 10 '18 at 10:27
  • Read [AngularJS FAQ - `$rootScope` exists, but it can be used for evil](https://docs.angularjs.org/misc/faq#-rootscope-exists-but-it-can-be-used-for-evil) – georgeawg Jul 10 '18 at 11:18

1 Answers1

0

Why is overusing $rootScope a bad practice?

The examples you are giving are better of to be stored inside a service or factory.

This way you can organize all the data and inject the correct data when ever needed.

By storing such properties inside the $rootScope, you end up with a huge object containing all sorts of data. Which makes it very hard to maintain if the project gets bigger.

If designing your application correctly, you won't even need the $rootScope.

Of course you could store everything inside the $rootScope, but you make it yourself and your collegues hard to maintain the application. And note that each variable set at the $rootScope are available to the controller $scope via prototypical inheritance.

enter image description here

Above picture is a console.log($scope). As you can see the $rootScope data is also available through there.

Storing simple things inside the $rootScope could be handy sometimes ofcourse. But I can't figure out what kind of thing I would assign to the $rootScope. Preferably store it inside services.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Red
  • 6,599
  • 9
  • 43
  • 85