如何在刷新后保留localStorage值?
问题描述:
这是我CTRL:如何在刷新后保留localStorage值?
app.controller('ctrl', function ($window, $scope) {
$scope.initData = [
{
firstName: "John",
lastName: "Doe",
},
{
firstName: "Jane",
lastName: "Doe",
},
{
firstName: "John",
lastName: "Smith",
}
];
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
$scope.retrievedData = JSON.parse($window.localStorage.getItem('initData'));
$scope.sortedType = 'firstName';
$scope.sortedReverse = false;
//Remove Rows and Update localStorage Key Values
$scope.removeRow = function(row) {
$scope.retrievedData.splice(row, 1);
$scope.initData.splice(row, 1);
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}
});
HTML:
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>
<span ng-show="sortedType == 'firstName' && sortedReverse" class="fa fa-long-arrow-up"></span>
<span ng-show="sortedType == 'firstName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
<span href="#" ng-click="sortedType = 'firstName'; sortedReverse = !sortedReverse" style="cursor:pointer;">First Name</span>
</th>
<th>
<span ng-show="sortedType == 'lastName' && sortedReverse" class="fa fa-long-arrow-up"></span>
<span ng-show="sortedType == 'lastName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
<span href="#" ng-click="sortedType = 'lastName'; sortedReverse = !sortedReverse" style="cursor:pointer;">Last Name</span>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(k, v) in retrievedData | orderBy: sortedType: sortedReverse">
<td>{{v.firstName}}</td>
<td>{{v.lastName}}</td>
<td>
<button class="btn btn-primary">Edit</button>
<button class="btn btn-primary" ng-click="removeRow();">Delete</button>
</td>
</tr>
</tbody>
</table>
现在,我认为这是明显的这是什么一样。它将$scope.initData
中的数据分配给localStorage
,然后将其插入到HTML中。功能removeRow()
将删除表中的行并使用最新操作更新localStorage
。与此相关的问题是,每次我重新加载HTML数据时,都会加载最初的localStorage
数据,而不是更新后的数据。我知道这是因为我在这里分配它:$window.localStorage.setItem('initData', JSON.stringify($scope.initData))
;但我不知道如何在刷新后保持更新。
请指教。
谢谢。
答
您的行$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
会在您每次刷新时重置数据。
这种替换行:
if(!localStorage.getItem('initData')){
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}
更多了,你不应该有该行的。从空的本地存储开始,仅从UI添加新条目。
上面的代码只运行一次,第一次运行应用程序。
如果哟想每一个列表为空时重新插入数据,那么试试下面
if(!localStorage.getItem('initData') || JSON.parse(localStorage.getItem('initData')).length === 0){
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}
答
在每一个页面加载你设置新initData和更新本地存储......相反,你应该检查现有localStorage的数据和使用,使用嘲笑initData
我应该有这条线..我需要有一些初始数据,因此线。 :) – tholo
然后,你应该添加条件检查,看看是否没有数据,然后只插入。 – BiJ
你还在吗?这有一个问题。 – tholo