2014-12-19 230 views
0

我現在正在修改此代碼,並且我想利用localStorage將我的小部件的狀態保存在儀表板上,以便當用戶返回到我的應用程序時,小部件的位置保持不變並保存,但每次刷新瀏覽器時,都會返回到當前的scope.dashboards狀態,我不知道如何修復。我用ngStorage模塊的localStorage當瀏覽器刷新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; 
+0

是你的網頁的本地(如訪問在瀏覽器中的文件),或者在服務器上? – atmd 2014-12-19 09:58:45

+0

也許與此相關:http://stackoverflow.com/questions/3738047/localstorage-doesnt-retrieve-values-after-page-refresh – atmd 2014-12-19 09:59:24

回答

0

我有用戶點擊調用此功能的按鈕:

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

}; 

那它保存到本地存儲。我也將它保存到數據庫,以防本地存儲過期或被刪除。

那麼當gridster加載我這樣做:

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