Storing an array in sessionStorage using AngularJS - What is the best approach?

In the process of building a website with HTML5 and AngularJS, I am utilizing a controller to interact with the database and set up an array called $scope.array.

Once the array is initialized, I store it in the session like this:

sessionStorage.array = $scope.array;

If there's already an existing array in the sessionStorage, I want to load that copy instead of creating a new empty array.

To achieve this, I have this logic in place:

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

This ensures that $scope.array contains the array data that I need to display via ng-repeat in the HTML.

However, my issue arises when I refresh the page for the first time, as the $scope.array object suddenly becomes an empty array (despite being initially populated with values from the database).

I'm looking for solutions on how to properly save the array in the session so that it never reaches the 'else' branch. Any advice would be greatly appreciated!

Answer №1

If I understand correctly, your requirement is for:

const data = localStorage.getItem("data");
$state.data = data ? JSON.parse(data) : [];

...

localStorage.setItem("data",JSON.stringify($scope.array));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inquire about Javascript appendChild Function

As I dive into learning JavaScript, I encountered an issue with my code. I have created a button that, when clicked, should append some text to all paragraphs on my page. However, for some reason, it's not working as expected. Here's my code: &l ...

What is the reason behind an Express function requiring both the Request and Response as parameters?

Exploring the world of node.js and familiarizing myself with Express. The code snippet below has left me puzzled: var server = http.createServer(handleRequest); function handleRequest(req, res) { var path = req.url; switch (path) { case "/n": ...

Sending information from controller to directive in angularjs

I'm currently facing an issue where I am attempting to send data from a controller to a directive in order to dynamically update rows in a table. However, despite my efforts, the table does not reflect any updates and there are no error messages displ ...

Struggling to click on a dynamic link before it times out

Can someone help me with a puzzling issue I can't seem to solve? I am trying to achieve the following: Whenever a link is clicked (for example: mysite.com/blog/blog-article.html), I want to save the href of that link to a variable. Then, in JavaScri ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

Mysterious line break emerges upon displaying JavaScript through PHP

I have a situation where I am using PHP to output JavaScript for a WordPress shortcode. This is what my PHP code looks like: $output="<script type='text/javascript' > jQuery(document).ready(function() { jQuery('#photo{$photo_id}&a ...

Unable to detect user's location after installing the apk on an Android device

I have developed a mobile app using Ionic AngularJS and ngCordova. I utilized the ngCordova geolocation plugin to retrieve the user's location. The application functions properly when tested on a browser. However, after installing the same app [androi ...

How does Django contribute to the functionality of single page applications?

I'm interested in developing my upcoming project with Django and AngularJS, but I find the division of responsibilities between the two frameworks a bit perplexing. To clarify, is it accurate to say that in this setup, Django will primarily manage au ...

Having trouble displaying the image on the screen with Material UI and React while using Higher Order Components (HOC) for

I'm facing an issue with displaying an image on my Material UI Card. Despite checking the directory and ensuring it's correct, the image still doesn't show up. Additionally, I need assistance in modularizing my code to avoid repetition. I at ...

The response from the $http POST request is not returning the expected

I am facing an issue where the $http POST method is not returning the expected response. The required data is located within config instead of data This is my Http POST request: for (var i = 0; i < filmService.filmData.length; i++) { filmData.pu ...

Sorting based on the number of elements in a filtered subdocument array

I have a MongoDB collection structured like this: { { "_id": ObjectId, "user_id": Number, "updates": [ { "_id": ObjectId, "mode": Number, "score": Number } ...

Interactive table created with DataTables that automatically updates the dynamic JSON data source whenever changes are made to the table

Using the Datatables plugin, I am dynamically populating a table with HTML rendered from a JSON array. However, I need the table to update the model (datasource) stored client-side whenever an edit is made. When navigating to a new page on the table, it s ...

I am having an issue with an input field not reflecting the data from the Redux state in my React app,

I am currently working on a todo list project using the MERN stack with Redux for state management. One issue I am facing is that the checkboxes for completed tasks are not reflecting the correct state from Redux when the page loads. Even though some tasks ...

Angular ng-repeat not recognizing nested ng-if conditions

Hey there, I'm trying to make sure that only the option corresponding to the code used by the client to log in is displayed. The HTML should show the option that matches the client's login code. View: <div class=""> <select id="custo ...

Remove the </div> text and replace it with nothing

I'm attempting to substitute the end tag div with an empty string. Here is my code: $('#textDiv').html().replace(/'</div>'/g,'').replace(/<div>/g,'\n') This is the HTML: <div id='tex ...

PHP's 'include' function is now being ported into modern Javascript as a new method

As the library of JS frameworks continues to expand, I'm wondering if there is a simple JS replacement or alternative for PHP's 'include' function. Is PHP include still a relevant method for including chunks of code, or are there better ...

Ways to eliminate an object from an array using Javascript or Jquery

I have two arrays of objects (with the same properties) where I need to remove all objects with the same name as those found in filesToRemove from the array files. However, when I attempt to use the code below, it throws an error: Uncaught TypeError: fil ...

Making a Linked List from an Array in C

Within the function, I initialized an array with a size of two to hold two PolyTerms. I then created a List and attempted to pass the array elements into the List as a linked list. However, I encountered an error after the if statement: head->next = no ...

Various methods for retrieving an element from an array

From my understanding, there are two methods for accessing elements in an array in C++: int array[5]; //If we have an array of 5 integers 1) Using square brackets array[i] 2) Using pointers *(array+i) The professor at my university insists on using t ...

Issue with Node.js Express app: HTML file not properly rendering, resulting in a blank page

Issue: I'm currently working on a Node.js application using Express. The objective is to serve an HTML file from the views folder, but when I try to access the page, it just shows a blank screen with no content. Code Snippet: const express = require( ...