HaloKiller HaloKiller -4 years ago 141
AngularJS Question

angularjs - How do I store an array inside sessionStorage?

I am developing a website using HTML5 and AngularJS, and inside the controller I access the database and initialize an array

$scope.array
.

Afterwards I save the initialized array in the session:

sessionStorage.array = $scope.array;


If that array exists in the sessionStorage, I want to load the sessionStorage copy, and not define an empty array.

I do it like so:

if(sessionStorage.array)
$scope.array = sessionStorage.array;
else
$scope.array = [];


So that
$scope.array
is the array I present to the HTML via
ng-repeat
.

But my problem is that after refreshing for the first time, the
$scope.array
object becomes an empty array (Before refreshing, it was initialized with values from the database)

How can I save the array in the session so that it won't get to the 'else' branch?

Answer Source

I assume you want

var arr = sessionStorage.getItem("array");
$scope.array = arr?JSON.parse(arr):[];

...

sessionStorage.setItem("array",JSON.stringify($scope.array));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download