Retrieving saved data from LocalStorage upon page reload

<div ng-repeat="section in filterSections">
    <h4>{{ section.title }}</h4>
    <div class="checkbox" ng-click="loaderStart()" ng-if="section.control == 'checkbox'" ng-repeat="option in section.options">
        <label>
            <input type="checkbox" ng-model="searchParams[section.key][option.key]" value="{{ option.key }}" checked><span></span> {{ option.value }}
        </label>
    </div>
</div>

I am able to access it by using $scope.searchParameters.

To save it, I can use

localStorage.setItem('search', JSON.stringify(cleanedParams));

To retrieve the saved data, I can use

JSON.parse(localStorage.getItem("search"));

One challenge I face is how to restore this data when the page is refreshed. Are there any specific functions or directives that could help with this? I have searched extensively but haven't found a solution tailored to my issue.

Answer №2

To implement this, start by creating an empty array and then add the desired values to it. From there, you can easily retrieve and manipulate the array elements using a loop.

let myArray = [];
myArray.push(JSON.parse(localStorage.getItem('data')));

Answer №3

To simplify handling JSON data, I've integrated ngStorage into my project. You can find more information about it here:

In all parts of my application (controllers, directives, services), I include the $localStorage provider and retrieve the stored data into the $scope:

app.controller("BarCtrl", ["$scope", "$localStorage", function($scope, $localStorage){

   $scope.savedData = $localStorage.dataFromStorage;

}]);

UPDATE: http://jsfiddle.net/Lvc0u55v/2997/

Answer №4

After some experimentation, I discovered a simple solution to inject the data directly back into $scope with minimal effort. This line of code did the trick:

$scope.searchParameters=JSON.parse(localStorage.getItem("search"));

Initially, I attempted to manually parse the entire dataset myself, but it proved to be more trouble than it was worth :)

Using the

$scope.$watch('searchParameters', function (newValue, oldValue)
function, I can now monitor changes to the element and update them accordingly in LocalStorage.

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

Automatically selecting checkboxes from an array using ReactJS

Hello there, I am a beginner working with react and I could really use some help with the issue below. Can you assist me? I am trying to figure out how to populate or check/uncheck checkboxes based on an Array's result. Specifically, I want to have ...

Tracking the advancement of synchronous XMLHttpRequest requests

Within the client-side environment, there exists a File-Dropzone utilizing the HTML5 File-API which allows users to drop multiple files for uploading to the server. Each file triggers the creation of a new XMLHttpRequest Object that asynchronously transfer ...

Extjs: How to Select a Node After Creating a Tree Structure

I am facing an issue with my TreePanel where I want to preselect a specific node when loading it. The nodes are fetched from a remote json file and the tree structure loads correctly. However, the selected node is not getting highlighted and Firebug is sho ...

What steps should I take in order to ensure that NPM commands run smoothly within Eclipse?

I have a functional workflow that I'm looking to enhance. Currently, I am developing a JavaScript library and conducting smoke tests on the code by using webpack to bundle the library and save it to a file that can be included in an HTML file for test ...

Creating HTML elements dynamically with attributes based on the `as` prop in React using TypeScript

Is there a way to dynamically create HTML elements such as b, a, h4, h3, or any element based on the as={""} prop in my function without using if guards? I have seen a similar question that involves styled components, but I am wondering if it can be done ...

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...

How can we compress videos on an Android device prior to uploading them through a web browser?

Can video compression be done prior to uploading via a web browser? For example, in iOS devices you can choose a video using the HTML input type file tag and iOS will automatically compress it before uploading. Are there any JavaScript or jQuery libraries ...

Uncertainty surrounding the extent of a button's scope within an Angular application

(click) event in one instance of a component is causing the function in another instance to be triggered unexpectedly. I am having trouble describing this issue. For reference, I have included a working example on stackblitz. When clicking on both buttons ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

Utilize jQuery to export HTML or JSON data to an Excel spreadsheet

I am looking for a way to export json or html data to an excel sheet using only html and jquery, without involving any server code. I have found some fiddles that allow me to download the excel sheet successfully, but unfortunately, none of them work in In ...

Is there a distinction between the node commands 'cordova ionic' and 'ionic'? Which command should be utilized?

When it comes to node commands, is there a distinction between running npm install -g cordova ionic versus just npm install -g ionic? Which of these commands should be used for building an Ionic project? It seems that the documentation provided by Ionic F ...

Using a static function within a library's state function in NextJS is throwing an error: "not a function"

Inside a library, there's a special class known as MyClass. This class contains a static method named setData. The contents of the MyClass.js file are shown below: class MyClass { static DATA = ''; static setData(data) { MyClass ...

Extract the body.req object within a loop in a Node.js application

I'm looking to efficiently parse and save the body of a POST request using Mongoose in Node.js. Is there a way to use a for loop to accomplish this task, rather than manually saving every property? My ideal solution would involve something like: for ...

Executing the callback function

I am facing a situation where I have a Modelmenu nested within the parent component. It is responsible for opening a modal window upon click. Additionally, there is a child component in the same parent component that also needs to trigger the opening of a ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Javascript encounters an unforeseen < token

I encountered an unexpected token < error in my JavaScript file. Despite checking the code using JSHint, I couldn't find any issues that could resolve the problem. I attempted to place the JavaScript code in a separate file and also tried embeddin ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

Ways to initiate a flip motion

Looking for a way to create a flip image effect when clicked by the user. Here is the code I have so far: let img = document.querySelector('img') let div; let click = 0; img.onclick=function(){ console.log(click) if(click %2 ==0){ d ...

Hmm, I seem to be encountering an error where res.sendStatus is not recognized as a function. What could be causing this

For the last few months, I have been immersed in Node.js/Express to create a REST Api. However, I've hit a roadblock with an async function in my controller.js file. The callback function is successfully receiving the client's request, but when i ...