angular ui grid save and restore state
Asked Answered
D

4

15

I need to know how to implement save and restore state in angularui grid without using any buttons. I need to save the state automatically when ever we do any changes in the grid. We have to auto restore the saved state also. Even if we refresh the page the saved state should be restored

Diu answered 2/9, 2015 at 6:50 Comment(1)
I'm not sure why you have been down voted. I am also trying to figure this out. Have you had any luck?Salmonoid
S
25

Here's what I figured out. I couldn't find a single event for grid state changes, but It does look like they have individual events for almost everything. Here are a few that i'm using. I just set a break point in the onRegisterApi callback and dug through the gridApi object to find the events. http://plnkr.co/edit/LAMZvOkpx6jsD4CWSz04?p=preview

HTML:

<div ui-grid="gridOptions"
     ui-grid-selection 
     ui-grid-resize-columns 
     ui-grid-auto-resize 
     ui-grid-move-columns 
     ui-grid-grouping 
     ui-grid-save-state>
</div>

JS:

$scope.gridOptions = {
  data: [
    { name: 'Jack', title: 'manager', phone: '123456789', location: 'india'},
    { name: 'Suzy', title: 'developer', phone: '465189798', location: 'usa'},
    { name: 'George', title: 'secretary', phone: '82656517', location: 'japan'},
    { name: 'Michael', title: 'analyst', phone: '31321687', location: 'egypt'},
    { name: 'Sara', title: 'consultant', phone: '59595847', location: 'germany'},
    { name: 'Chris', title: 'engineer', phone: '789456123', location: 'russia'},
    { name: 'Elizabeth', title: 'clerk', phone: '963852741', location: 'china'},
    { name: 'Jane', title: 'intern', phone: '147258369', location: 'australia'},
    { name: 'Bill', title: 'accountant', phone: '951487623', location: 'brazil'}
  ],
  columnDefs: [
    { name: 'name' },
    { name: 'title' },
    { name: 'phone' },
    { name: 'location' }
  ],
  enableGridMenu: true,
  enableRowSelection: true,
  enableRowHeaderSelection: false,
  enableColumnResizing: true,
  enableColumnReordering: true,
  enableFiltering: true,
  onRegisterApi: function(gridApi) {
    // Keep a reference to the gridApi.
    $scope.gridApi = gridApi;

    // Setup events so we're notified when grid state changes.
    $scope.gridApi.colMovable.on.columnPositionChanged($scope, saveState);
    $scope.gridApi.colResizable.on.columnSizeChanged($scope, saveState);
    $scope.gridApi.grouping.on.aggregationChanged($scope, saveState);
    $scope.gridApi.grouping.on.groupingChanged($scope, saveState);
    $scope.gridApi.core.on.columnVisibilityChanged($scope, saveState);
    $scope.gridApi.core.on.filterChanged($scope, saveState);
    $scope.gridApi.core.on.sortChanged($scope, saveState);

    // Restore previously saved state.
    restoreState();
  }
};

function saveState() {
  var state = $scope.gridApi.saveState.save();
  localStorageService.set('gridState', state);
}

function restoreState() {
  $timeout(function() {
    var state = localStorageService.get('gridState');
    if (state) $scope.gridApi.saveState.restore($scope, state);
  });
}
Salmonoid answered 9/9, 2015 at 17:55 Comment(2)
Wrapping the restoreState function with $timeout is key, as it would not apply the restored state without adding that.Electroshock
Can I put saveState and restoreState into service? There's $scope obj that can't be passed to the function in the service. I have lots of grid tables located at different controllers, I want to have their state saved but don't want to write the same function in each controller, how can I achieve this?Finite
C
0

Here's a service easy to use with localforage

angular.module('starter.controllers')
    .factory('SaveStateGridService', function SaveStateGridService($timeout, $state, $rootScope) {
        var self = {
            stateName: null,
            keyLocalStorage: null,
            listener: null,
            init: function (gridApi) {

                self.stateName = $state.$current.name;
                self.keyLocalStorage = 'grid-' + self.stateName;

                if (self.keyLocalStorage != null) {

                    // save the state before we leave
                    self.listerner = $rootScope.$on('$stateChangeStart',
                        function (event, toState, toParams, fromState, fromParams, options) {
                            if (fromState.name === self.stateName) {
                                var item = gridApi.saveState.save();
                                localforage.setItem(self.keyLocalStorage, item);
                            }
                            self.listerner();
                        }
                    );

                    //restore the state when we load if it exists
                    localforage.getItem(self.keyLocalStorage, function (err, item) {
                        if (item != null) {
                            $timeout(function () {
                                gridApi.saveState.restore(null, item);
                            }, 1);
                        }
                    });

                }

            }
        };
        return self;
    });

Controller / Component

 $scope.gridOptions.onRegisterApi = function (gridApi) {  
   SaveStateGridService.init(gridApi); 
 };

Html

 <div
      ui-grid="gridOptions"
      ui-grid-save-state></div>
Chorea answered 25/9, 2017 at 16:56 Comment(0)
A
0

it's relatively easy to save the state using Angular $cookies

    function saveState() {
  var state = $scope.gridApi.saveState.save();
        $cookies.put('gridState', JSON.stringify(state));
}

Then, to restore:

$scope.restoreState = function() {
     $timeout(function() {
    var state = JSON.parse($cookies.get('gridState'));
    if (state) {
        $scope.gridApi.saveState.restore($scope, state);
}
Aldenalder answered 15/11, 2017 at 1:2 Comment(1)
cookies doesn't work: angular.js:14791 Cookie 'gridState' possibly not set or overflowed because it was too large (9040 > 4096 bytes)!Glavin
C
-2

I couldn't find a single event for grid state changes =>

                window.onbeforeunload = function(e) {
                $scope.saveState();
            };
            $scope.restoreState();

in case you want to reset the grid

                if(localStorage.getItem("justReset")!="1")
                $scope.restoreState();
            localStorage.setItem("justReset","0")
Clarsach answered 7/10, 2015 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.