Created
September 25, 2017 16:51
-
-
Save dam1/29006d7a82335a7a241b19d034f0975f to your computer and use it in GitHub Desktop.
Angular Ui Grid save state Service with localforage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$scope.gridOptions.onRegisterApi = function (gridApi) { | |
SaveStateGridService.init(gridApi); | |
}; | |
<div | |
ui-grid="gridOptions" | |
ui-grid-save-state></div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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