How to remove an item from localStorage using a loop in AngularJS

I am struggling to figure out how to delete an element in localStorage within a loop. In the save method, I add elements and check for duplicates. Can you please explain how I can delete an element using only the id or all values?

My Factory

.factory('SaveDocuments', function() {
        var documents = [];

            save: function (id, name, link) {
                if(documents.filter(function(a){return a.id==id}).length)
                { alert('conflict!'); }
                else {
                // add to it,
                documents.push({id: id, name: name, link: link});
                // then put it back.
                localStorage.setItem('document', JSON.stringify(documents));
                }

            },

            del: function(id, name, link) {
                if(documents.filter(function(a){return a.id==id}).length) {
                    for (i = 0; i < localStorage.length; i++){
                    key = localStorage.key(i);
                    value = localStorage.getItem(key);
                        localStorage.removeItem(value);
                    console.log(value);
                    break;
                }
                }
                else {
                    alert('conflict!');
                }
            }

        }

MyController

 .controller('PageSearchCtrl', function($scope, ConstSearch, SaveDocuments) {                          
     $scope.saveDocument = function() {                                                                
         //Create new project                                                                          
             $scope.document = [{"id": 1, "name": "new1", "link": "#/const"}];              
             SaveDocuments.save($scope.document[0].id,$scope.document[0].name,$scope.document[0].link);
     };                                                                                                
      $scope.deleteDocument = function () {                                                            
          $scope.document = [{"id": 1, "name": "new1", "link": "#/const"}];                 
          //Create new project                                                                         


SaveDocuments.del($scope.document[0].id,$scope.document[0].name,$scope.document[0].link);    
  }             

Answer №1

It would be beneficial to update your service implementation with something similar to the following:

.factory('SaveDocuments', function () {
    var lsKey = 'document',
        documents = JSON.parse(localStorage.getItem(lsKey) || '[]');

    function saveToLocalStorage() {
        localStorage.setItem(lsKey, JSON.stringify(documents));
    }

    return {
        save: function (id, name, link) {
            if (documents.filter(function (a) {
                return a.id == id;
            }).length) {
                alert('conflict!');
            } else {
                documents.push({
                    id: id,
                    name: name,
                    link: link
                });
                saveToLocalStorage();
            }

        },

        del: function (id, name, link) {
            
            if (!id && !name && !link) {
                documents = [];
                saveToLocalStorage();
                return;
            }
            var initialLength = documents.length;
            documents = documents.filter(function (doc) {
                return (!id || doc.id !== id) && (!name || doc.name !== name) && (!link || doc.link !== link);
            });
           
            if (documents.length === initialLength) {
                alert('conflict!');
            } else {
                saveToLocalStorage();
            }
        }
    };
});

Keep in mind that I initialized it properly from local storage upon application start, utilized a variable for storing the key used in local storage (for code efficiency), and improved the del() method to retain unmatched data or delete all when no arguments are provided, then updates the local storage with the modified data.

Note: Ensure to test this as I have not conducted any testing to confirm functionality.

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

An error was caught: the object is not iterable and cannot read the property Symbol(Symbol.iterator) within the XMLHttpRequest function

const container = document.querySelector("#box"); request.open("GET","https://api.data.com/population/us"); request.send(); // To retrieve the response request.addEventListener("load",function(){ // console.log(this.responseText); const [da ...

Tips for efficiently organizing and maintaining a selection of JavaScript variables by easily adding and removing them as needed

I am currently developing items that will be shown on a webpage. I achieve this by utilizing the following code: var popup = "something..." Is there a method to keep track of all the created popup variables and control them efficiently using: adding a ...

Injecting environment variables into webpack configuration

My goal is to set a BACKEND environment variable in order for our VueJS project to communicate with the API hosted there, but I keep receiving an error message saying Unexpected token :. Here is the current code snippet from our config/dev.env.js, and I&a ...

The error message "Express Routing - Attempting to access property 'include' of undefined" is displayed when an

I am attempting to implement basic routing based on the user's selections on the first page. If the user picks 2 out of 3 options on the parent page, I want them to only see those two child pages and not the third. My strategy for the parent page was ...

Transform JSON data into a string separated by commas with an array embedded within

I've been trying to work with a JSON data but can't seem to convert it as needed. Here is the JSON structure: {"domiciles":[{"country":"AF"},{"country":"AX"},{"country":"AL"}],"investor":[{"type":"ii"},{"type":"pi"}]} It's stored in sessio ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

What is the best way to send a message to only one specific client using socket.io instead of broadcasting to everyone?

After thoroughly researching the documentation, I am still unable to find a solution. My goal is to send data to a specific client or user instead of broadcasting it to everyone. I have come across other inquiries regarding this issue, but most either rem ...

Is it possible to utilize node-inspector for debugging a node.js application that is being executed with foreman?

One of my node.js applications can be debugged using node-inspector with the command: node --debug app.js However, I prefer to use foreman to start the application in order to load environment variables from the .env file. This is done by running: forem ...

jQuery efficiently handles large amounts of text data transfer (gradual loading)

The issue at hand: My website relies on jQuery AJAX (post) for navigation, meaning the page doesn't refresh every time a user moves to a different section. This setup requires me to fetch data using AJAX and present it dynamically. While this works w ...

The power of AngularJS lies in its ability to create

I have been studying AngularJS directives and found a valuable resource at this link: Directives One particular example that caught my attention is about: Creating Directives that Communicate As I was going through the code snippet in script.js, I stumbl ...

Steps for integrating a Facebook Messenger chatbot with a MongoDB database in order to submit requests and retrieve responses through conversations with the bot

I am currently working on integrating my Facebook Messenger chatbot with a MongoDB database. The chatbot I have created is a simple questionnaire chatbot that takes text inputs and displays buttons with options. When a user clicks on a button, it should ...

Retrieve data from AJAX once the cycle is complete

Currently, I am attempting to calculate the sum of results from an external API by making a single request for each keyword I possess. The code is functioning properly; however, the function returns the value before all the ajax requests are completed. Eve ...

Ways to manually change the history in angular.js

Currently, I am facing a challenge in removing the querystring (specifically an invitation token) from the URL without triggering a page redirect. Here is an example of what the URL looks like: example.com/?invitation=fooo In our project, we are using n ...

the process of attaching an event listener to every item in a list and accessing them individually

When you click on an item in the list, it will switch the .done class on and off. <ul> <li class="bold red" random="23">Notebook <button>Delete</button></li> <li>Jello <button>Delete</button></l ...

What exactly does a 'hoisted manifest' mean when it comes to using Yarn?

Encountering an issue while attempting to install a package using yarn, I am receiving the error message: expected hoisted manifest for \"myPackage#@material-ui/core#react-dom\" However, the concept of a 'hoisted manifest' is not entir ...

The progress bar seems to be malfunctioning

Need help with my progress bar, it's not working properly. Can someone assist me? var x = document.getElementById("p_bar"); for(var i = 0; i < 100; i++) { var wid; wid=1; if(wid == 800) break; else wid+=8; x.style.width=wid+" ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

Executing a function on each page within the head tag in Nuxt.js

I successfully made my function accessible by using the plugin attribute in the nuxt.config.js file, allowing me to call the function under mounted on every page. I am looking for a more efficient way to run this function within the head tag and have it b ...

Unable to execute main JS template in Angular partial view, JQuery function also fails to work on the partial view

As a newcomer to angular, I am facing a challenge with the JS file that I have initiated on the index.html page. While working with angular, I have had to create partial views of different pages. The functions in this file handle tasks such as minimizing a ...

What steps can be taken to ensure that the getData() function is executed prior to the MovieCard

Struggling to work with async functions while creating a random movie generator app using react js and material ui. It seems like the data retrieval from the API is not quick enough for my component. How can I fix this issue? Is there a way to ensure tha ...