How to keep localStorage values after refresh?

2020-02-12 17:28发布

问题:

This is my ctrl:

app.controller('ctrl', function ($window, $scope) {

    $scope.initData = [
        {
            firstName: "John",
            lastName: "Doe",  
        },
        {
            firstName: "Jane",
            lastName: "Doe",
        },
        {
            firstName: "John",
            lastName: "Smith",
        }
    ];

    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
    $scope.retrievedData = JSON.parse($window.localStorage.getItem('initData'));
    $scope.sortedType = 'firstName';
    $scope.sortedReverse = false;
    //Remove Rows and Update localStorage Key Values
    $scope.removeRow = function(row) {
        $scope.retrievedData.splice(row, 1);
        $scope.initData.splice(row, 1);
        $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
    }
});

HTML:

<table class="table table-bordered table-striped table-hover">
                <thead>
                <tr>
                    <th>
                        <span ng-show="sortedType == 'firstName' && sortedReverse" class="fa fa-long-arrow-up"></span>
                        <span ng-show="sortedType == 'firstName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
                        <span href="#" ng-click="sortedType = 'firstName'; sortedReverse = !sortedReverse" style="cursor:pointer;">First Name</span>
                    </th>
                    <th>
                        <span ng-show="sortedType == 'lastName' && sortedReverse" class="fa fa-long-arrow-up"></span>
                        <span ng-show="sortedType == 'lastName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
                        <span href="#" ng-click="sortedType = 'lastName'; sortedReverse = !sortedReverse" style="cursor:pointer;">Last Name</span>
                    </th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="(k, v) in retrievedData | orderBy: sortedType: sortedReverse">
                <td>{{v.firstName}}</td>
                <td>{{v.lastName}}</td>
                <td>
                    <button class="btn btn-primary">Edit</button>
                    <button class="btn btn-primary" ng-click="removeRow();">Delete</button>
                </td>
            </tr>
            </tbody>
        </table>

Now, I believe it is clear what this does. It is assigning a data from $scope.initData to localStorage and then interpolate it into the HTML. the function removeRow() deletes the row in the table and updates the localStorage with the latest action. The issue with this is that each time I reload the HTML the initial localStorage data gets loaded and not the updated one. I know that this is because I'm assigning it here: $window.localStorage.setItem('initData', JSON.stringify($scope.initData)); but I don't know how to keep it updated after the refresh.

Please advise.

Thanks.

回答1:

Your line $window.localStorage.setItem('initData', JSON.stringify($scope.initData)); is resetting the data each time you refresh.

Replace the line with this:

if(!localStorage.getItem('initData')){
    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}

More over you should not have that line at all. Start with an empty local storage and add new entries from UI only.

The above code only run it once, for the first time the application is run.

If yo want to re-insert the data every time the list is empty then try following

if(!localStorage.getItem('initData') || JSON.parse(localStorage.getItem('initData')).length === 0){
    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}


回答2:

On every page load you are setting new initData and updating the local storage... Instead you should check for existing localstorage data and use that before using the mocked initData



回答3:

You need to check first if your localStorage is empty on load

if (localStorage == null) {//setItem() ...};


回答4:

delete data from local storage using JavaScript Here is your code without error passed.

use function for delete

       function deleteRow(index){
              dataList.splice(index, 1);
              console.log('====>', dataList)
              localStorage.setItem('items', JSON.stringify(dataList)); 
}


回答5:

This code will help you to understand.....

<!DOCTYPE html>
    <html>
    <head>
    <script>
    var ArrayData = [];
    function clickCounter() {
        if(typeof(Storage) !== "undefined") {
            if (localStorage.count) {
                localStorage.count = Number(localStorage.count)+1;
            } else {
                localStorage.count = 1;
            }
            document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.count;
        } else {
            document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
        }
    }
    function load()
    {
        var odser = JSON.parse(localStorage.getItem("data"));
        document.getElementById("result1").innerHTML = odser;
    }
    function fun()
    {
        var odser = JSON.parse(localStorage.getItem("data"));
        ArrayData = odser;
        ArrayData.push(3);
        var oser = JSON.stringify(ArrayData);
        localStorage.setItem("data", oser);
        var odser = JSON.parse(localStorage.getItem("data"));
        document.getElementById("result1").innerHTML = odser;
    }
    </script>
    </head>
    <body onload="load()">
    <button onclick="clickCounter()" type="button">Click me!</button>
    <button onclick="fun()" type="button">Click me! Array</button>
    <div id="result"></div>
    <div id="result1"></div>
    </body>
    </html>


回答6:

In Simple Steps in matters how you need your page to refresh using afunction to refresh comes handy and effective for me and keeps the locaStorage values set.. i used.... the function below by calling it as load() and it worked for me

    function load()
{
  console.log("loading")
  setTimeout("window.location.assign('samepage.html');", 1000);

}