The use of $rootScope
to do what you seek. Services (service
and factory
) of AngularJs
are there for that.
Why not use $rootScope?
$rootScope
, as the name says, is a scopo of root, 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
, a new value may be changed, deleted and/or inserted.
Working with short and simple applications, no problem. But when you start working with several controller
that need this data, eventually you can create a $scope
which has nothing to do with the $rootScope
but that modifies that value. Or that 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 where he left off? Using the same previously stored data? Or $rootScope
will be reset to its initial state?
Note: Most importantly, do not fall into the temptation to create a function using $rootScope
.
When to use $rootScope?
It is more advisable to use the $rootScope
only for global definitions that are unchanged. Ex.: Name of the application, name of the user logged in a welcome message (There is still to analyze this one), finally. Data you will not modify (or at least not as often).
What to use?
As you have already commented that you are using localStorage
, I recommend you stick with it. Your control will be much better about the data you need/handle, and you can reuse the data if the user leaves the application and comes back later. You can still set an expiration date for that information.
Note: Still maintains the url
clean, without a lot of data.
Remarks
Logically all of this should be taken into account by analyzing the size/complexity of your application vs actual enhancements/optimizations you will have.
The use of $rootScope
really should be avoided, but it is not always feasible to create this whole scenario to manipulate the data if it is something simple.
It really worked. Thank you.
– leopiazzoli
Imagine haha! :)
– luckakashi