Когда браузер обновляет localStorage, сбрасывается

Сейчас я работаю над этим кодом, и я хотел бы использовать localStorage для сохранения состояния моих виджетов на моей панели инструментов, чтобы, когда пользователь возвращается в мое приложение, положение виджетов не менялось и сохранялось, но каждый раз, когда я обновляю браузер он возвращается к своему текущему состоянию scope.dashboards, которое я понятия не имею, как мне это исправить. Я использовал модуль ngStorage для localStorage.

var modInProgr = false;
    $scope.$watch("dashboards['1'].widgets", function(newVal, oldVal) {
        if (!modInProgr) {
            modInProgr = true;
            // modify dashboards
            $scope.$storage = $localStorage;
            $localStorage.sample = $scope.dashboards[1];
            console.log($localStorage.sample);
        }
        $timeout(function() {
            modInProgr = false;
        }, 0);

        $scope.dashboard = $localStorage.sample;
    }, true);

    // init dashboard

    $scope.dashboard = $localStorage.sample;

person bluestella    schedule 19.12.2014    source источник
comment
ваша страница локальна (как при доступе к файлу в вашем браузере) или на сервере?   -  person atmd    schedule 19.12.2014
comment
Возможно, это связано с этим: stackoverflow. ком/вопросы/3738047/   -  person atmd    schedule 19.12.2014


Ответы (1)


У меня есть кнопка, которую пользователь нажимает, чтобы вызвать эту функцию:

//Used to save the dashboard to BOTH local storage and PENN database
//Local storage will attempt to be loaded first. However, if local storage is not there
//then we will load the dashboard from the database
$scope.serialize = function() {

    $scope.dashboardJSON = angular.toJson($scope.standardItems);

    console.log($scope.dashboardJSON);

    localStorageService.set("DashboardInfo", $scope.dashboardJSON);

    //Send HTTP request 'POST' to saveDashboard function in Rails controller
    $http({
        method: 'POST',
        url: 'saveDashboard',
        data: {'dashboardInfo': $scope.dashboardJSON },
        headers: {'Content-Type': 'application/json' }
        }).success(function(data, status, headers, config)
        {
            //Let user know that their dashboard was saved with this success flash
            $scope.successSavingDashboardToDBAlert();
        }).error(function(data, status, headers, config)
        {
            //Let the user know the dashboard could not be saved with this error flash
            $scope.errorSavingDashboardToDBAlert();
        }); 

};

Это сохраняет его в локальном хранилище. Я также сохраняю его в базу данных на случай, если локальное хранилище истечет или будет удалено.

затем, когда гридстер загружается, я делаю это:

var dashboardInfo = localStorageService.get("DashboardInfo");

if (dashboardInfo == null)
{
          //Load from the database
}
else
{
           //console.log("Loading from Local Storage");

              //Parse the local storage JSON data with angular
             var parsedDashboard = angular.fromJson(dashboardInfo);

              //Loop through the parsed data to push it to the array that is used for gridster. 
              //Usually this is called items but in my case I called it standardItems

            for(var i = 0; i < parsedDashboard.length; i++)
            {
                 //console.log(parsedDashboard[i]);
                 $scope.standardItems.push(parsedDashboard[i]);
            }
                     //$scope.successAlert();
}
person Jakepens71    schedule 07.10.2015