Search code examples
angularjsangular-ui-grid

AngularJS ui grid save and restore state not working


The grid doesn't seem to save and restore states even though I use the saveState module and I can't figure out why. There is no error in the console. Everything seems to be running, save & restore functions are called properly and yet the grid doesn't keep the changes I make. Any ideas what might be causing the problem?

                            self.storage.gridApi.core.on.columnVisibilityChanged($scope, saveState);
                            self.storage.gridApi.colMovable.on.columnPositionChanged($scope, saveState);

                            restoreState();

                            function saveState() {
                                var state = self.storage.gridApi.saveState.save();
                                localStorage.setItem(self.list.id + 'grid', state);
                            }

                            function restoreState() {
                                $timeout(function() {
                                    var state = localStorage.getItem(self.list.id + 'grid');
                                    if (state) {
                                        self.storage.gridApi.saveState.restore($scope, state);
                                    }
                                });
                            }
            <div ui-grid="vm.gridOptions" flex class="af-ui-grid"
                 ui-grid-infinite-scroll
                <?php if ($this->isGranted('subscriber.entry') || $this->isGranted('subscriber.entry')) { ?>
                    ui-grid-selection
                <?php } ?>
                 ui-grid-resize-columns
                 ui-grid-auto-resize
                 ui-grid-exporter
                 ui-grid-move-columns
                 ui-grid-save-state></div>
    'ui.grid.infiniteScroll',
    'ui.grid.selection',
    'ui.grid.resizeColumns',
    'ui.grid.moveColumns',
    'ui.grid.saveState',
    'ui.grid.autoResize',
    'ui.grid.exporter',
    'ui.grid.edit',

Solution

  • Fixed by using JSON.parse/stringify.

                                function saveState() {
                                let state = self.storage.gridApi.saveState.save();
                                localStorage.setItem(self.list.id, JSON.stringify(state));
                            }
    
                            function restoreState() {
                                $timeout(function() {
                                    let state = JSON.parse(localStorage.getItem(self.list.id));
                                    if (state) {
                                        self.storage.gridApi.saveState.restore($scope, state);
                                    }
                                });
                            }