【发布时间】:2017-06-15 02:57:27
【问题描述】:
这是我的 ctrl:
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'));
console.log($scope.retrievedData);
$scope.sortedType = 'firstName';
$scope.sortedReverse = false;
$scope.removeRow = function (row) {
$scope.retrievedData.splice(row, 1);
$window.localStorage.removeItem('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>
我的ng-controller 和ng-app 是在html 中分配的,所以我们不必担心。 removeRow() 函数在这里发生的事情是我设法删除了该行,但我也需要它从 localStorage 中删除它。此时,执行$window.localStorage.removeItem('initData'); 不是一种选择,因为它会删除整个对象。我该怎么做?
如何删除localStorage 中仅包含随行删除的数据的部分?
编辑:我知道我无法编辑键值,但如何设置新键值?将$window.localStorage.setItem('initData', JSON.stringify($scope.initData)); 放在函数中并没有真正的帮助。
SOLUTIN:感谢回答的人。我已通过添加以下内容来修复它:$scope.initData.splice(row, 1); 低于$scope.retrievedData.splice(row, 1); 我发现我已经在row 参数中使用了索引。之后我写了:$window.localStorage.setItem('initData', JSON.stringify($scope.initData)); 谢谢。
【问题讨论】:
标签: javascript jquery angularjs html local-storage