我不确定这是否被推荐,但我创建了一个 StateService 来保存/加载控制器范围内的属性。它看起来像这样:
(function(){
'use strict';
angular.module('app').service('StateService', function(){
var _states = {};
var _save = function(name, scope, fields){
if(!_states[name])
_states[name] = {};
for(var i=0; i<fields.length; i++){
_states[name][fields[i]] = scope[fields[i]];
}
}
var _load = function(name, scope, fields){
if(!_states[name])
return scope;
for(var i=0; i<fields.length; i++){
if(typeof _states[name][fields[i]] !== 'undefined')
scope[fields[i]] = _states[name][fields[i]];
}
return scope;
}
// ===== Return exposed functions ===== //
return({
save: _save,
load: _load
});
});
})();
为了使用它,我在控制器的末尾放了一些代码,如下所示:
angular.module('app').controller('ExampleCtrl', ['$scope', 'StateService', function ($scope, StateService) {
$scope.keyword = '';
$scope.people = [];
...
var saveStateFields = ['keyword','people'];
$scope = StateService.load('ExampleCtrl', $scope, saveStateFields);
$scope.$on('$destroy', function() {
StateService.save('ExampleCtrl', $scope, saveStateFields);
});
}]);