【问题标题】:local-storage not displaying values after page reloads页面重新加载后本地存储不显示值
【发布时间】:2016-12-21 19:38:16
【问题描述】:

我正在使用 angularjs 制作计时器应用程序,单击时间列表后计数器开始,可以通过单击添加计时器来添加时间列表中的新时间(弹出窗口打开,然后使用时间选择器选择时间)。 选择的时间被添加到列表中以及单击 OK 按钮的本地存储。 但是当页面重新加载时,不会显示时间列表中新添加的时间,而是驻留在 localStorage 变量中(即 timeListDetails)。 我希望在添加新计时器时显示它。

获取和设置本地存储值的代码:

$scope.getStoredTimeList = function(){
            timeList = JSON.parse(localStorage.getItem("timeListDetails")) || [];
            if(timeList != null){
              timeList.push({"hour":hour,
                                    "minutes":minutes,
                                    "seconds":seconds,
                                    "convertedSec":convertedSec,
                                    "timeFlag": true});
            }
            $scope.timeList = $scope.timeList.concat(timeList).unique();

            localStorage.setItem("timeListDetails", JSON.stringify(timeList));
          }

我已经完成了我的完整示例。 Clock Application review

请告诉我解决方法。

【问题讨论】:

    标签: angularjs html local-storage html-framework-7


    【解决方案1】:

    这是因为您没有在页面重新加载或初始化应用程序时调用 getStoredTimeList 方法。 方法:

    getStoredTimeList()
    

    仅在 sibmit()

    您应该首先在应用初始化时从 localStorage 恢复值。

    【讨论】:

    • 我也试过这个解决方案,它给出了类似“小时、分钟、秒”的列表,低于“12 小时、17 分钟、56 秒”
    • 我已经更新了同样的plunk,谢谢你的帮助。
    【解决方案2】:

    当重新加载页面时 $scope.timeList 值迭代 ng-repeat 你在控制器中给出的内容。

    我的想法只是比较 localStorage.getItem("timeListDetails") 和 $scope.timeList,如果不同,您可以使用 localstorage 并分配给 $scope.timeList,否则让它成为值。

    简单的例子..

    $scope.timeList = [
                      {"hour":0, "minutes":1, "seconds": 6},
                      {"hour":0, "minutes":3, "seconds": 180},
                      {"hour":0, "minutes":5, "seconds": 300}];
     var temp = JSON.parse(localStorage.getItem("timeListDetails"));
                var checkObj = angular.equals($scope.timeList, temp);
                if(!checkObj){
                  angular.copy(temp, $scope.timeList);
                }
    

    也在这里更改..第一次发生当您尝试推送时,如果任何一个值未定义,例如 sec。我认为(小时或分钟或秒)未定义是有问题的。

    if(timeList != null){
                  timeList.push({"hour":hour || 0,
                                        "minutes":minutes || 0,
                                        "seconds":seconds || 0,
                                        "convertedSec":convertedSec || 0,
                                        "timeFlag": true});
                }
    

    根据您的需要使用其他方式..

    【讨论】:

    • 我得到了解决方案,更新了同样的问题。谢谢你的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多