Javascript 根据表(索引)的行删除localStorage键
这是我的ctrl:Javascript 根据表(索引)的行删除localStorage键,javascript,jquery,angularjs,html,local-storage,Javascript,Jquery,Angularjs,Html,Local Storage,这是我的ctrl: app.controller('ctrl', function ($window, $scope) { $scope.initData = [ { firstName: "John", lastName: "Doe", }, { firstName: "Jane", lastName: "Doe", },
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:
名字
姓
{{v.firstName}
{{v.lastName}
编辑
删去
我的ng控制器
和ng应用程序
是在html中分配的,因此我们不必担心这一点。使用removeow()
函数时,我会设法删除该行,但我也需要它从localStorage
中删除该行。此时,执行$window.localStorage.removietem('initData')代码>不是选项,因为它删除整个对象。我该怎么做
如何删除localStorage
中仅包含随行删除的数据的部分
编辑:我知道我不能编辑键值,但如何设置新的键值?放置$window.localStorage.setItem('initData',JSON.stringify($scope.initData))函数中的code>并没有真正的帮助
苏琳:多亏了那些回答的人。我通过添加:$scope.initData.splice(第1行)修复了它代码>下面$scope.retrievedData.splice(第1行)
我发现我已经在行
参数中使用了索引。之后我写了:$window.localStorage.setItem('initData',JSON.stringify($scope.initData))代码>谢谢。无法编辑localStorage值的内容,只能覆盖它
您应该做的是编辑$scope.initData
,然后使用$window.localStorage.setItem('initData',JSON.stringify($scope.initData))代码>以覆盖它
您需要将单击更改为ng click=“removeRow($index)”
($index
是当前重复的元素索引),然后将其添加到函数中
$scope.removeow=函数(行索引){
$scope.retrievedData.splice(行索引,1);
$window.localStorage.setItem('initData',JSON.stringify($scope.retrievedData));
}
由于u在再次保存到localstorage之前更改了retrievedData
,因此它将具有数据的新值-即没有行。如何知道已删除了哪个数组索引?将$index
哪个是行号发送到removeRow函数,然后拼接(索引,1)
<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>