を削除これは私の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'));
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));
を配置しても、実際には役に立ちません。
ソルティン:答えた人のおかげです。私はそれを追加して修正しました:$scope.retrievedData.splice(row, 1);
row
引数のインデックスを使用していることが分かりました。その後、私は書いた:$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
ありがとう。
どのアレイインデックスが削除されているかをどのように知ることができますか? – tholo
行番号である '$ index'をremoveRow関数に送り、' splice(index、1) ' – Nayish
答えを編集してください。 – tholo