我需要在我的下拉菜单中添加一个ngchange以保存到localstorage,这样当某人关闭应用程序时,仍然会保存更改。现在一切正常,但是当重新加载应用程序时,用户必须再次进行选择。我如何让它工作?
这是HTML:
<select ng-model="item" ng-options="category.title for category in categories | filter: 234 | filter: {title: '!Federal'} "
ng-change="changedValue(item)" style="text-align: left;">
<option value="" selected="selected">Choose a State</option>
</select>
这是JavaScript:
$scope.changedValue = function(item) {
$scope.categories.push(item.id);
console.log(item.id);
$localStorage.id = item.id;
console.log($scope.categories);
$scope.categories = $localStorage.categories;
$http.get('http://mywebsite.com/api/get_category_posts/?id=' + item.id).then(
function(data){
$scope.category_posts = data.data.posts;
答案 0 :(得分:2)
您可以将数据存储在本地存储中
localStorage.setItem('ID', item.id);
因此,您可以在重新加载后获取数据
$scope.categories = localStorage.getItem('ID');
答案 1 :(得分:2)
在LocalStorage中设置项目:
var lastSelected = JSON.parse(localStorage.getItem('selectedOption'));
从LocalStorage获取项目:
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", function($scope) {
$scope.categories = [
{
"title":"uttarakhand",
"name":"uttarakhand"
},
{
"title":"himachal",
"name":"himachal"
},
{
"title":"telangana",
"name":"telangana"
}
];
var lastSelected = JSON.parse(localStorage.getItem('selectedOption'));
if(lastSelected) {
$scope.item = lastSelected;
}
$scope.changedValue = function(item) {
localStorage.setItem('selectedOption', JSON.stringify(item));
};
});
<强>样本强>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select ng-model="item" ng-options="category.title for category in categories"
ng-change="changedValue(item)" style="text-align: left;">
<option value="" selected="selected">Choose a State</option>
</select>
</div>
let samples = [0.01, -0.02, -0.02, 0.01, -0.01, -0.01, 0.00, 0.10, 0.31,
-0.10, -0.73, -0.68, 0.21, 1.22, 0.67, -0.59, -1.04, 0.06, 0.42, 0.07,
0.03, -0.18, 0.11, -0.06, -0.02, 0.16, 0.21, 0.03, -0.68, -0.89, 0.18,
1.31, 0.66, 0.07, -1.62, -0.16, 0.67, 0.19, -0.42, 0.23, -0.05, -0.01,
0.03, 0.06, 0.27, 0.15, -0.50, -1.18, 0.11, 1.30, 0.93, 0.16, -1.32,
-0.10, 0.55, 0.23, -0.03, -0.23, 0.16, -0.04, 0.01, 0.12, 0.35, -0.38,
-1.11, 0.07, 1.46, 0.61, -0.68, -1.16, 0.29, 0.54, -0.05, 0.02, -0.01,
0.12, 0.23, 0.29, -0.75, -0.95, 0.11, 1.51, 0.70, -0.30, -1.48, 0.13,
0.50, 0.18, -0.06, -0.01, -0.02, 0.03, -0.02, 0.06, 0.03, 0.03, 0.02,
-0.01, 0.01, 0.02, 0.01]
答案 2 :(得分:1)
如果您想在localStorage中存储任何内容,那么您可以按照以下方式进行操作。它应该有一个关键和价值。
localStorage.setItem('category', 'PRODUCTS');
如果您想获得相同的内容,请使用密钥。在您需要的地方,使用以下行获取数据
localStorage.getItem('category');