我有一個簡單的表,它正從localStorage
加載數據。點擊刪除按鈕後,行被刪除(每次點擊1次),從localStorage
刪除鍵。在AngularJS中排序時刪除行和localStorage密鑰
TL; DR orderBy
導致失去指數
的軌道現在,這個問題發生了,當我已經介紹了「排序」和「反向排序」功能。爲了簡化故事,這裏是我的代碼。
<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>
ctrl.js:
app.controller('ctrl', function ($window, $scope) {
$scope.initData = [
{
firstName: "John",
lastName: "Doe",
},
{
firstName: "Jane",
lastName: "Doe",
},
{
firstName: "John",
lastName: "Smith",
}
];
if(!localStorage.getItem('initData')) {
$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));
}
});
這到底是怎麼發生的,當我對數據進行排序(它是由firstName
自動排序),或者當我做反向排序,並單擊刪除,該刪除的第一行始終是我的array
中的第一個object
。所以,可以說我想刪除"John Smith"
所在的行,並且我點擊「刪除」按鈕,「John Doe"
」對象被刪除,我試圖通過.indexOf()
來解決這個問題,但我不能。已經試過:
$scope.removeRow = function(rowIndex) {
var index = $scope.retrievedData.indexOf(rowIndex);
$scope.retrievedData.splice(index, 1);
$scope.initData.splice(index, 1);
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
console.log($scope.retrievedData.indexOf(rowIndex));
}
所以,我試圖保持指數的跟蹤與.indexOf()
,但我console.log()
輸出-1
現在的最後一個對象被刪除
我能在這裏做
?謝謝。
給我一分鐘,請,但爲什麼我的方法不起作用,明明使用的indexOf找到對象的數組對象的索引() ? – tholo
我認爲indexOf()在字符串或數字的數組上工作。什麼是rowIndex?您沒有將HTML中的任何參數傳遞給removeRow()函數。 – Vivz
哦,你是對的..在這個函數中可以傳遞什麼作爲參數? – tholo