We do not recommend using $rootScope
to do what you are looking for. The services ( service
and factory
) of AngularJs
are there for this.
Why not use $ rootScope?
$rootScope
, as the name already says, is a root scopo, common and accessible in all controller
that you own. If you create a $rootScope
with the name sales: $rootScope.vendas
it will be accessible in all controller
, can be changed, deleted and / or inserted a new value.
Working with short and simple applications, no problem. But when you start working with multiple controller
who need this data, you can eventually create a $scope
that has nothing to do with $rootScope
but modifies that value. Or you end up losing control of which function is modifying that $rootScope
.
Another point, if the user leaves the application and comes back later, will he be able to continue from where he left off? Using the same data stored previously? Or will $rootScope
be reset to its initial state?
Note: Most importantly, do not be tempted to create a function using $rootScope
.
When to use $ rootScope?
We recommend using $rootScope
only for global settings that do not change. Ex .: Name of the application, name of the user logged in welcome message (Still to analyze this), anyway. Data that you will not modify (or at least not so often).
What to use?
Since you already said that you are using localStorage
, I recommend that you stick with it. Your control will be much better about the data you need / manipulate, as well as being able to reuse the data if the user exits the application and comes back later. You can still set an expiration time for that information.
Note: It still keeps url
clean, without a lot of data.
Observations
Of course all this should be taken into consideration by analyzing the size / complexity of your application vs. actual improvements / optimizations that you will have.
The use of $rootScope
should really be avoided, but it is not always feasible to create this whole scenario to manipulate the data if it is something simple.