使用AngularJS防止在Localstorage中添加重复项

时间:2016-02-24 16:17:07

标签: javascript angularjs local-storage

我正在研究将产品(如收藏夹)存储到localStorage的原型,但我正在努力检查localStorage中是否已存在某个项目,因此不会再次添加。

检查重复条目并优雅处理的最佳位置在哪里?

我的样本控制器如下:

function dCtrl($scope, $filter) {

    $scope.d = [
        {id:'1',d_name:'Product 1',colour:'Blue'},
        {id:'2',d_name:'Product 2',colour:'Red'},
        {id:'3',d_name:'Product 3',colour:'Cream'},
        {id:'4',d_name:'Product 4',colour:'White'},
        {id:'5',d_name:'Product 5',colour:'Green'},
        {id:'6',d_name:'Product 6',colour:'Black'},
        {id:'7',d_name:'Product 7',colour:'Purple'},
        {id:'8',d_name:'Product 8',colour:'Grey'},
        {id:'9',d_name:'Product 9',colour:'Yellow'},
        {id:'10',d_name:'Product 10',colour:'Indigo'}
    ];

  $scope.getDetails = function (id, favDresses) {

      //get the object of the item clicked
      single_object = $filter('filter')($scope.d, {id:id})[0];
      // If you want to see the result, check console.log
      console.log(single_object); 
      console.log('ID:' + id + ' - save this object to localStorage');

      //set localstorage var
      var storage = localStorage.getItem('newfavdresses');

      //check to see if the localStorage array is empty (not null)
      if(storage != null) {

        //if it isnt, parse the string
        favDresses = JSON.parse(localStorage.getItem('newfavdresses'));
        //push into the array
        favDresses.push(single_object);
        //set the item in localstorage
        localStorage.setItem("newfavdresses",JSON.stringify(favDresses));

      } else {

        //if the array is null, create it
        var favDresses = [];
        //and push the item into it
        favDresses.push(single_object);
        //set the item in local storage
        localStorage.setItem("newfavdresses",JSON.stringify(favDresses));

      }

  }

  $scope.clearStorage = function() {
    localStorage.clear();
    alert('Local Storage Cleared');
  }

//get localStorage items  
var dresses = localStorage.getItem("newfavdresses");
dresses = JSON.parse(dresses);
console.log(dresses);

}

jsFiddle演示 - https://jsfiddle.net/dwhiteside86/Lt7aP/2261/

2 个答案:

答案 0 :(得分:1)

我的建议是使用存储在服务中的实时javascript数组。

当服务初始化时,您将从localStorage加载此数组,如果存储中没有任何内容,则将其设置为空数组。

然后,无论何时更新存储的数组,您总是将整个内容存储到localStorage中,以便存储的版本始终是实时版本的字符串副本。

这样您只需使用getItem()一次,然后使用一个简单的服务方法storeLocal(),每次修改数组中的数组或对象时都会调用它。

您可能会看到的另一件事是ngStorage为您完成以上所有操作

答案 1 :(得分:0)

看看https://github.com/grevory/angular-local-storage,我相信它会解决你的所有问题。该库将您的scope属性绑定到本地存储,因此您不会关心它的存储方式。