2015-09-04 168 views
0
复制到本地存储

我用Angular.js的localStorage的值存储在本地如何避免Angular.js

这里是plnkr Demo

一切工作正常,但如何避免将产品或值两次? (如何避免重复),同时将值推送到本地

回答

2

您只需将项目推送到数组而无需在cloneItem()中进行任何进一步检查。您可以更新其实施重复检查第(只是一个快速的想法):

$scope.cloneItem = function (todo) { 

    // Check for duplicate on id 
    if($scope.$storage.notes.filter(function (note) { 
     return note.id === todo.id; 
    }).length > 0) { 
     return; 
    }; 

    // Insert if not duplicate 
    $scope.$storage.notes.push({ 
     "price": todo.price, 
     "id": todo.id, 
     "quan": todo.quan 
    }); 
} 
+0

伟大的工作正常..谢谢快速信息! –

1

我想你可以使用更短的方式比萨科一个:

$scope.cloneItem = function (todo) { 

    if ($scope.$storage.notes.indexOf(todo) == -1) { 
    //if the object is not in the array 
     $scope.$storage.notes.push({ 
      "price": todo.price, 
      "id": todo.id, 
      "quan": todo.quan 
     }); 
    } 
    //else you just do nothing 
}