What's (technically) the difference between state management and using $rootScope in AngularJS?

264 Views Asked by At

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.

1

There are 1 best solutions below

2
Red On

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.