我正在尝试将本地存储值分配给$ scope变量,并在ng-model中使用该$ scope变量来初始化下拉列表。我尝试下面的代码,但它无法正常工作。
以下是plunker:https://plnkr.co/edit/Ile7ehzxB9PcoeTKk1B6?p=preview
我只需要从本地存储初始化它,因为我只通过本地存储接收数据。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('appNew', []);
app.controller('controllerNew', function($scope) {
$scope.dataSet = ["A", "B", "C"];
localStorage['color'] = {"A":"Red","B":"Red","C":"Blue"};
var colorVar = localStorage['color'] || '';
$scope.selectColor = colorVar;
});
</script>
</head>
<body ng-app="appNew">
<table class="table TableOne" ng-controller="controllerNew">
<thead>
<tr>
<th>Serial</th>
<th>Data</th>
<th>Dropdown</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in dataSet">
<td>{{$index + 1}}</td>
<td>{{data}}</td>
<td>
<select ng-model="$parent.selectColor[data]">
<option value="">-- Select --</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>
</td>
</tr>
</tbody>
</table>
</body>
</html>
答案 0 :(得分:2)
LocalStorage允许存储目前的键/值对 - 请参阅doc here:
Web Storage API提供了浏览器可以存储的机制 键/值对,比使用cookie更直观。
所以你可以stringify
存储对象,parse
将它们从本地存储中取回,如下所示:
localStorage['color'] = JSON.stringify({"A": "Red","B": "Red","C": "Blue"});
$scope.selectColor = JSON.parse(localStorage['color']);
请参阅下面的代码段 - 由于限制,代码段可能无效 - 请查看plnkr code here
。
var app = angular.module('appNew', []);
app.controller('controllerNew', function($scope) {
$scope.dataSet = ["A", "B", "C"];
localStorage['color'] = JSON.stringify({"A": "Red","B": "Red","C": "Blue"});
$scope.selectColor = JSON.parse(localStorage['color']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="appNew">
<table class="table TableOne" ng-controller="controllerNew">
<thead>
<tr>
<th>Serial</th>
<th>Data</th>
<th>Dropdown</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in dataSet">
<td>{{$index + 1}}</td>
<td>{{data}}</td>
<td>
<select ng-model="selectColor[data]">
<option value="">-- Select --</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>
</td>
</tr>
</tbody>
</table>
</body>