尝试使用ngStorage
简而言之
一个模块,使得可以轻松地在AngularJS中使用LocalStorage。
据说如果LocalStorage不可用,它会使用Cookie作为替代。
- https://github.com/agrublev/angularLocalStorage
实际上有点像”angularLocalStorage”。
准备
按照这个参考,生成AngularJS项目的模板。
$ bower install ngStorage --save
添加依赖关系。
angular.module('myApp', ['angularLocalStorage']);
尝试使用
绑定
会自动进行同步。
angular.module('myApp')
.controller('myCtrl', function($scope, storage) {
var defaultValue = {id: 1, name: 'hoge'};
storage.bind($scope, 'myValue', {defaultValue: defaultValue});
});
设定
angular.module('myApp')
.controller('myCtrl', function($scope, storage) {
storage.set('test', {id: 1, name: 'hoge'});
});
取得
angular.module('myApp')
.controller('myCtrl', function($scope, storage) {
$scope.val = storage.get('test');
});
清空所有
angular.module('myApp')
.controller('myCtrl', function($scope, storage) {
storage.clearAll();
});
获取键
angular.module('myApp')
.controller('myCtrl', function($scope, storage) {
console.log(storage.getKeys());
});