Skip to content

Instantly share code, notes, and snippets.

@dam1
Created September 25, 2017 16:51
Show Gist options
  • Save dam1/29006d7a82335a7a241b19d034f0975f to your computer and use it in GitHub Desktop.
Save dam1/29006d7a82335a7a241b19d034f0975f to your computer and use it in GitHub Desktop.
Angular Ui Grid save state Service with localforage
$scope.gridOptions.onRegisterApi = function (gridApi) {
SaveStateGridService.init(gridApi);
};
<div
ui-grid="gridOptions"
ui-grid-save-state></div>
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;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment