Restore value when going back a view

I’m trying to figure out how to store a value and have it restored when going back to the view.

In essence, I have 2 pages: About and Details. You can go to Details from About page. On click, I store a value. From Details, when I go back, I want this value to restored. Basically, I don’t want it to be fully persistent throughout the app, just for this lifespan of going back to a view.

Is this possible to achieve and how? For instance, is there a way to listen to the back event?

** I started looking at the source code for $ionicScrollDelegate, which has this rememberScrollPosition functionality, which is kind of what I want to achieve but with storing my own custom values. https://github.com/driftyco/ionic/blob/b7859553483ad59b246ca36d9f91327544dd9868/js/angular/controller/scrollController.js

Ok, so I’ve been reading on the $viewHistory (viewService) source code and think I found the solution.

To determine if you are going back to this view, you have to check:

if ($rootScope.$viewHistory.forwardView) {
// Came back from details view for example.
}

I’ve been testing this a bit and been getting exactly what I wanted. https://github.com/driftyco/ionic/blob/b87bcb30c33fb577b41139c43089b2a864211d56/js/angular/service/viewService.js

You should really be creating and using a service (factory) to do this.

VERY simplistic example :

.factory('MyService', function() {
	
	var storedValue;

	return {

		getStoredValue = function() {
			return storedValue
		},

		setStoredValue = function(value) {
			storedValue = value
		}
	}


})
.controller('MyCtrl', ['$scope', 'MyService', function($scope, MyService) {
	
	$scope.data = {
		specialValue : MyService.getStoredValue()
	}

}])
1 Like