How to keep localStorage values after refresh?

时间:2017-06-15 10:12:01

标签: javascript jquery html angularjs local-storage

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.

7 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分: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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

使用JavaScript从本地存储中删除数据 这是您的代码没有错误传递。

使用删除功能

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

答案 4 :(得分:0)

此代码将帮助您了解.....

<!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>

答案 5 :(得分:0)

在“简单步骤”中,您如何需要使用函数刷新来刷新页面对我来说很方便且有效,并保持了locaStorage值设置。我使用了...。下面的函数通过将其称为load()和它对我有用

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

}

答案 6 :(得分:0)

几个月来我一直面临着同样的问题。最后我找到了解决方案。 (我不确定这对你来说是否是同样的问题,无论如何分享我的场景)

当我在本地主机上进行测试时,我使用 URL 作为 http://localhost:3000/ 来加载页面。但是在登录时,页面刷新后,我实际上是使用 IP 地址来重定向页面,就像 http://192.163.1.31:3000/

所以结果,http://localhost:3000/的本地存储包含我保存的值,但http://192.163.1.31:3000/的本地存储不包含我保存的值。

所以我通过在整个启动过程中简单地使用相同的 URL 来修复解决方案,直到页面加载。问题得到了解决。 (我使用了 http://192.163.1.31:3000/ 而不是 http://localhost:3000/)

对于您的情况,请检查页面重新加载后网址是否不同。如果是,请修复它,您的问题可能不会持续