It depends on your situation, but if you do not want to save the state after reloading the page, for which localStorage would be useful, but rather, the state is remembered only when you return (and not necessarily when you later go back and forth to the view again ), then I do this: I do a separate service, just an object around which I can embed anywhere and store some variables. In Angular 1, this will be a service object.
angular.module('foo').factory("placeHelper", [ () => { let _place = null; class PlaceHelper { set place(place){ _place = place; } get place(){ return _place; } reset(){ _place = null; } } let helper = new PlaceHelper(); return helper; } ]);
Then in your controller that you are returning to, you add placeHelper and request it for the place and restore your state via $scope.place = placeHelper.place , and when someone selects a place in the user interface for this controller, you just store it in placeHelper.place = $scope.place .
I would use localStorage inside the service if I wanted to maintain state after page refresh.
I don't like the contamination of $ rootScope because itโs harder to keep track of when you start to have more than a few unrelated methods, and your properties should have longer names (or grouped by objects anyway). This is best for serviceability for encapsulation and separation of problems.
Service change: A service can be an object literal instead of a class, and you can directly set properties instead of using methods if you want it to be a little easier.
angular.module('foo').factory("placeHelper", [ () => { let helper = { place: null, reset(){ this.place = null; } }; return helper; } ]);
source share