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


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:

$scope.array = sessionStorage.array;
$scope.array = [];

So that
is the array I present to the HTML via

But my problem is that after refreshing for the first time, the
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):[];


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download