我需要知道如何在不使用任何按钮的情况下在angularui网格中实现保存和恢复状态。当我们在网格中进行任何更改时,我需要自动保存状态。我们还必须自动恢复已保存的状态。即使我们刷新页面,也应恢复已保存的状态
答案 0 :(得分:0)
这是一项易于使用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;
});
控制器/组件
$scope.gridOptions.onRegisterApi = function (gridApi) {
SaveStateGridService.init(gridApi);
};
HTML
<div
ui-grid="gridOptions"
ui-grid-save-state></div>
答案 1 :(得分:0)
使用Angular $ cookies保存状态相对容易
function saveState() {
var state = $scope.gridApi.saveState.save();
$cookies.put('gridState', JSON.stringify(state));
}
然后,恢复:
$scope.restoreState = function() {
$timeout(function() {
var state = JSON.parse($cookies.get('gridState'));
if (state) {
$scope.gridApi.saveState.restore($scope, state);
}
答案 2 :(得分:-2)
我无法找到网格状态更改的单个事件=&gt;
window.onbeforeunload = function(e) {
$scope.saveState();
};
$scope.restoreState();
如果您想重置网格
if(localStorage.getItem("justReset")!="1")
$scope.restoreState();
localStorage.setItem("justReset","0")