我正在尝试使用本地存储保存标签。它不起作用,我不知道它发生了什么。
app.js:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.tags = [
{ text: 'Tag1' },
{ text: 'Tag2' },
{ text: 'Tag3' }
];
});
的index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.15"></script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<tags-input ng-model="tags"></tags-input>
<p>Model: {{tags}}</p>
</body>
</html>
我正在尝试使用localStorage在用户离开应用程序,返回到另一个页面或只刷新它时让标记保留在那里。
window.localStorage['name'] = {{tags}};
链接到doc: http://learn.ionicframework.com/formulas/localstorage/
答案 0 :(得分:1)
您需要将标签模型保存到localStorage并在每次集合更改时更新它:删除/添加标签。为此创建帮助程序服务很方便:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http, storage) {
$scope.tags = storage.get('tags') || [
{ text: 'Tag1' },
{ text: 'Tag2' },
{ text: 'Tag3' }
];
$scope.$watchCollection('tags', function(tags) {
storage.set('tags', tags);
});
});
app.factory('storage', function() {
return {
get: function(key) {
return JSON.parse(localStorage[key] || 'null');
},
set: function(key, value) {
window.localStorage[key] = JSON.stringify(value);
}
};
});
注意,如何在控制器代码中首先检查存储的项目,如果不可用,则回退到默认标记:
$scope.tags = storage.get('tags') || [
{ text: 'Tag1' },
{ text: 'Tag2' },
{ text: 'Tag3' }
];
答案 1 :(得分:0)
此代码将读取localStorage中的标记,将其放在控制器
中function isBitSet(no, index) {
var bin = no.toString(2);
// Convert to Binary
index = bin.length - index;
// Reverse the index, start from right to left
return bin[index] == 1;
}
isBitSet(44, 2); // Check if second bit is set from left
此代码会将标记保存到localStorage:
$scope.tags = JSON.parse(window.localStorage['tags'] || '[]');
例如,您的控制器将是这样的:
window.localStorage['tags'] = JSON.stringify($scope.tags);