AngularJS -从$window.localStorage中移除特定数组项

AngularJS - Removing specific array item from $window.localStorage

本文关键字:数组 window localStorage AngularJS      更新时间:2023-09-26

我想做一个小的Angular web应用程序,我把数组上的项目设置为$window。localStorage,然后在另一个页面上获取数组并显示它。

我已经为每个数组项做了一个"删除"按钮,但是当我按下它时,它会清除整个localStorage,而不仅仅是一个特定的项。

<table class="table table-striped">
    <tr ng-repeat="product in productss track by $index">
        <td>{{product.name}}</td>
        <td><button class="glyphicon glyphicon-remove-circle shoplisticons-remove" ng-click="deleteProduct(product)"></button></td>
    </tr>
</table>

JS

helloApp.controller("StorageCtrl", function($scope, $window, productService) {
    $scope.productss = productService.getData();
    $scope.deleteProduct = function(product) {
        var index = $scope.productss.indexOf(product);
        $scope.productss.splice(index, 1);
        $window.localStorage.removeItem($window.localStorage.key(product));
    };
});
//Array, add and get:
helloApp.service('productService', function($window) {
    var KEY = 'helloApp.SelectedValue';
    var addData = function(newObj) {
        var mydata = $window.localStorage.getItem(KEY);
        if (mydata) {
            mydata = JSON.parse(mydata);
        } else {
            mydata = [];
        }
        mydata.push(newObj);
        $window.localStorage.setItem(KEY, JSON.stringify(mydata));
    };
    var getData = function() {
        var mydata = $window.localStorage.getItem(KEY);
        if (mydata) {
            mydata = JSON.parse(mydata);
        }
        return mydata || [];
    };
    return {
        addData: addData,
        getData: getData
    };
});

希望我说得够详细

在这一行中,您将删除整个项目。

 $window.localStorage.removeItem($window.localStorage.key(product));

我相信您希望在删除元素后将数组保存到本地存储。关键是您应该在将产品删除到localStorage后设置数组。你这样做

helloApp.controller("StorageCtrl", function($scope, $window, productService) {
$scope.productss = productService.getData();
$scope.deleteProduct = function (product) {
     var index = $scope.productss.indexOf(product);
     $scope.productss.splice(index, 1);
     $window.localStorage.setItem('helloApp.SelectedValue',JSON.stringfy($scope.productss));
};

或者为了更优雅的解决方案,您可以在服务中添加一个函数来设置数据

这是因为您要删除整个项目。别忘了你把它作为字符串存储在localStorage中,所以localStorage不知道它是一个对象数组。

要删除一个项目,您必须从localStorage获取整个数组,将其解析为JSON,使用索引拼接项目,并在localStorage

中设置新数组。