这是我的代码。我使用$ localStorage将对象推送到数组中。当我单击按钮时,对象被正确推入并再次拼接相同的对象,然后单击相同的按钮。 $ localStorage.tableArray分配给$ scope.Storage下拉列表。按钮操作完成后,下拉列表会很好。
我的问题是$ scope。$ storage有两个项目。如果我刷新页面下拉列表没有来。 如果我按下按钮下拉列表上的推动或拼接动作就会好起来。
请在刷新页面时帮助如何将$ scope。$ storage项目放入下拉列表中。 我为此创建了一个plunker。检查一次
HTML:
<body ng-controller="MainCtrl">
<a class="btn {{table.btnClass}} btn-success" ng-repeat="table in tablelist" ng-click="getTable(table)" style="padding-left:1px">{{table.tablename}}</a>
<select ng-options="table.tablename as table.tablename for table in $storage" ng-model="table.tablename"><option value="">---select table---</option></select>
JS:
var app = angular.module('plunker', ["ngStorage"]);
app.controller('MainCtrl', function ($scope,$localStorage,$filter) {
$scope.tablelist = [{ "tablename": "t1" }, { "tablename": "t2" },{ "tablename": "t3" },{ "tablename": "t4" }]
if ($localStorage.tableArray === undefined) {
$localStorage.tableArray = []
}
if ($localStorage.tableslist === undefined) {
$localStorage.tableslist = []
}
angular.forEach($scope.tablelist, function (list, $index) {
var found = $filter('filter')($localStorage.tableArray, { tablename: list.tablename }, true);
if (found.length) {
$scope.tablelist[$index].btnClass = found[0].btnClass;
}
});
$scope.getTable = function (table) {
table.btnClass = table.btnClass == "btn-danger" ? "btn-success" : "btn-danger"
var exists = false;
angular.forEach($localStorage.tableArray, function (list, $index) {
if ((list.tablename == table.tablename)) {
console.log(list.tablename)
console.log(table.tablename)
exists = true;
$localStorage.tableArray.splice($index, 1)
$localStorage.tableslist.splice($index, 1)
$scope.$storage= $localStorage.tableArray;
console.log( $scope.$storage)
return false
}
});
if (!exists) {
$localStorage.tableslist.push(table)
$localStorage.tableArray = $localStorage.tableslist;
$scope.$storage = $localStorage.tableArray
console.log($localStorage.tableArray)
table.color = "red"
}
}
});
答案 0 :(得分:1)
根据我的理解,您希望在刷新时使用localstorage中存储的值初始化下拉列表。
在控制器中添加以下行可以为我工作:
public Dictionary<string, string> dic { get; set; } = new Dictionary<string, string>();
检查plnkr