AngularJs localStorage在循环中删除元素

AngularJs localStorage delete element in loop

本文关键字:删除 元素 循环 localStorage AngularJs      更新时间:2023-09-26

我不知道如何删除localStorage循环中的元素在保存方法中,我添加元素并检查它是否重复请解释我如何删除元素,例如只使用id或所有值

我的工厂

.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);    
  }             

我建议将您的服务更改为以下内容:

.factory('SaveDocuments', function () {
    var lsKey = 'document', // the key to store the docs in local storage under
        documents = JSON.parse(localStorage.getItem(lsKey) || '[]'); // initialise from localStorage
    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 {
                // add to it,
                documents.push({
                    id: id,
                    name: name,
                    link: link
                });
                saveToLocalStorage();
            }
        },
        del: function (id, name, link) {
            // clear all if del() is called with no arguments or null for all args
            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 nothing was removed, show error
            if (documents.length === initialLength) {
                alert('conflict!');
            } else {
                saveToLocalStorage();
            }
        }
    };
});

请注意,当应用程序启动时,我从本地存储状态正确地初始化了它(因此,当您重新加载页面时,数据正确地在那里),使用一个变量来保存您用于在本地存储中存储数据的唯一键(以保持代码DRY),并修复了您的del()方法,使其保留不符合删除条件的方法,或者在没有传入参数的情况下删除所有内容,然后用更新后的状态覆盖本地存储器中的值。

注意:你应该测试一下,我没有做任何测试来看看这是否有效。