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

Error: The function res.getHeader is not recognized within the Next.js API environment

I am currently working on a web application using NextJS 13, TypeScript, Next Auth v4, Prisma (using SQLite for development), and OpenAI. While accessing the API endpoint, I encountered an error in the console with the following message: error - TypeError ...

Tips for enabling a keypad to restrict input field character limit

Encountering an issue with an input field that has a maximum length of 6 characters. Typing normally seems to work fine, but when using a custom keypad, the limit is not enforced and it allows for more than 6 characters to be entered. HTML: <div cl ...

Presenting a trio of distinct tables each accompanied by its own unique button option

I am attempting to create a functionality where there are 3 buttons and when a user clicks on one of them, it shows the corresponding table while hiding the other two. I have experimented with using getElementById to manipulate the display property of the ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

Code for refreshing content using AJAX

I'm looking for AJAX code to set a value in a session. For instance: $_SESSION['verif_code'] I want to generate a random number and assign it to this session. I need some AJAX code to refresh this random number function and set the value ...

Sending multiple unique forms with the same structure using JavaScript and Ajax on a single PHP page

In my PHP page, there are 12 individual forms with unique form IDs, checkboxes, and dropdowns. Take a look at this image: https://i.stack.imgur.com/pODzk.png Each form has an Update Zone that fetches Name, Enable status, Time, Dim information, and sends ...

AngularJS factory or filter failing to update properly

I have been working on a system that manages translations in my factory. I set the language as a string and then use a filter to update the view when the language changes. Everything works fine if I define the language in the view beforehand, but when I t ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

What is the best way to implement auto-refreshing with reactQuery?

Hey there! I'm currently working with a GraphQL API and I'm trying to automatically refetch data at regular intervals (e.g. every 3 seconds). I've been using React Query and have tried some workarounds like using setInterval, but it's n ...

The data from my API is not showing up in my React application

Im working on a project where I am trying to retrieve an image of a recipe card from and display it on my react.js application. However, I am encountering difficulties in getting the API data to show up on the page when running the code. Any assistance wo ...

Using jQuery to retrieve the nth child from a table after dynamically creating it with AJAX

When using AJAX in the code below, I fill and create simple data after retrieving it. $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: false, success: function (data ...

How can I match the date format of d-M-Y using JavaScript regex?

When it comes to date formatting in PHP, I typically use the format d-M-Y. Recently, I attempted to match these dates using a JavaScript regex: s.match(new RegExp(/^(\d{1,2})(\-)(\w{3})(\-)(\d{4})$/)) I wanted to use this regex w ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

Obscure unidentified attribute within JSON error object

In my node.js console script, I am utilizing pg-promise. Node version: v0.10.38 pg-promise version: 1.1.4 A connection error occurred due to a simple misconfiguration issue that was not very informative. I would like my script to provide a detailed expla ...

navigating through an array with a loop (for)

I created a basic phone book program where users can input a name and it will search an array of objects for the corresponding phone number. If the name is found, it will display the name and phone number. However, I am facing an issue where even though ...

When you hover over them, Material UI icons shrink in size due to the Border

I've been working on a React application that includes Material UI icons in the header. My goal is to add a border at the bottom of each icon when hovered over, but currently, the borders are too close to the icons. Another problem I'm facing is ...

Revamp the current webpage to display attribute values in textual format

As I peruse a webpage, I notice that there is room for improvement in terms of user-friendliness. The page is filled with a list of movie titles, each accompanied by a link to IMDb. However, the IMDB user rating is only visible when hovering over the titl ...

Display historical data upon clicking in AngularJS

Check out this PLUNK for the current scenario. In my HTML file, I have a div where JSON data is displayed using ng-repeat. The JSON data is structured in a nested form. Within the div, there's an anchor tag that, when clicked, shows the children of t ...

How can I stop Jquery Mobile from processing the URL hash?

Currently implementing Jquery Mobile in a preexisting web application is posing a challenge. The issue arises as Jquery Mobile is interpreting all URL hashes by default. For example: mysite.com/#foo In this case, the hash 'foo' is being directe ...