页面重新加载后本地存储不显示值

local-storage not displaying values after page reloads

我正在使用 angularjs 制作计时器应用程序,点击时间列表后计数器开始,可以通过点击添加计时器在时间列表中添加新时间(弹出窗口打开然后使用时间选择器选择时间)。 选择的时间被添加到列表中以及单击确定按钮的本地存储。 但是当页面重新加载时,时间列表中新添加的时间不会显示,而是驻留在 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

请告诉我解决方法。

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

getStoredTimeList()

仅在 sibmit()

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

每当重新加载页面时 $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});
            }

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