Search code examples
angularlocal-storageangular-uiangular-ui-gridsavestate

Angular ui grid restore state not working


I'm trying to save the state of an angular grid so when you go back to the grid the user can restore where you left it.

I get no errors when I click save or restore.

The grid does not change when you click restore after you save the grid.

What am I doing wrong?

$scope.saveState = function(){
     console.log("Saving")
     var state = $scope.gridApi.saveState.save();
     $window.localStorage.setItem('gridState', state);
     console.log("Saving done")
};

$scope.restoreState = function(){
    console.log("Restoring")
    var state = $window.localStorage.getItem('gridState');
    if (state) $scope.gridApi.saveState.restore($scope, state);
    console.log("Restoring done")
};

Solution

  • For anyone else having this problem I found out that $window.localStorage can not save objects.

    To work around this you can use JSON.stringify

      $scope.saveState = function(){
            console.log("Saving")
            var state = $scope.gridApi.saveState.save();
            console.log(state)
            $window.localStorage.setItem('gridState', JSON.stringify(state));
            console.log("Saving done")
       };
    
       function restoreState(){
            console.log("Restoring")
            $timeout(function() {
               var state = $window.localStorage.getItem('gridState');
               console.log(state)
               if (state) $scope.gridApi.saveState.restore($scope, JSON.parse(state));
            });
            console.log("Restoring done")
       };