gpt4 book ai didi

javascript - 如何将 ngChange 保存在本地存储中

转载 作者:行者123 更新时间:2023-11-28 13:09:38 25 4
gpt4 key购买 nike

我的下拉菜单中需要一个 ngchange 来保存到本地存储,这样当有人关闭应用程序时,更改仍然会保存。现在一切正常,但是当应用程序重新加载时,用户必须再次进行选择。我怎样才能让它发挥作用?

这是 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;

最佳答案

在 LocalStorage 中设置项目:

localStorage.setItem('selectedOption', JSON.stringify(item));

从 LocalStorage 获取项目:

var lastSelected = JSON.parse(localStorage.getItem('selectedOption'));

演示

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>

关于javascript - 如何将 ngChange 保存在本地存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43581410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com