Reputation: 1863
In my angularjs application, I have the following list of objects.
$scope.itemsList = [
{
"setupId": "T_2893",
"name" : "abc"
},
{
"setupId": "LBT826",
"name" : "xyz"
},
{
"setupId": "LBT1252",
"name" : "pqr"
},
{
"setupId": "G1252",
"name" : "dwr"
}
]
Now when I call $scope.changeOreder(1, 3) function it should reorder the objects based on the prev and next index. so the list should be as follows.
$scope.itemsList = [
{
"setupId": "T_2893",
"name" : "abc"
},
{
"setupId": "LBT1252",
"name" : "pqr"
},
{
"setupId": "G1252",
"name" : "dwr"
},
{
"setupId": "LBT826",
"name" : "xyz"
}
]
Now if I call, $scope.changeOreder(2, 0)
, the new list should be,
$scope.itemsList = [
{
"setupId": "G1252",
"name" : "dwr"
},
{
"setupId": "T_2893",
"name" : "abc"
},
{
"setupId": "LBT1252",
"name" : "pqr"
},
{
"setupId": "LBT826",
"name" : "xyz"
}
]
In my $scope.changeOrder function, I have tried different ways, like taking the back up of the object at prevIndex
, then deleting the obj at prevIndex
to insert the backed up obj at newIndex
, but because I have deleted the object the newIndex
is no more valid in the current list!!!. Like this I tried different different ways but the final list is not getting ordered the way I am expecting. Can any one help me in fixing it.
Upvotes: 0
Views: 246
Reputation: 2876
Moving an item to a specified index:
var items = [
{
"setupId": "G1252",
"name" : "dwr"
},
{
"setupId": "T_2893",
"name" : "abc"
},
{
"setupId": "LBT1252",
"name" : "pqr"
},
{
"setupId": "LBT826",
"name" : "xyz"
}
];
function moveItem(posA, posB) {
/*
* If an item is moved from a higher index to a lower index, then we need to
* remove the current item first, then add it.
* When moving a item from a low index to a higer index, then we need to add
* the item first, then delete it.
*/
var upToDown = posA > posB;
var itemToMove = items[posA];
//Make copy first
var tmpList = items.slice(0);
if (!upToDown) {
//Add item to specified index
tmpList.splice(posB+1, 0, itemToMove);
//Remove the old item
tmpList.splice(posA, 1);
} else {
//Remove the old item
tmpList.splice(posA, 1);
//Add item to specified index
tmpList.splice(posB, 0, itemToMove);
}
return tmpList;
}
var result = moveItem(0, 3);
console.log(result);
Plunk: https://plnkr.co/edit/23DGzcXBEY7qrqFWsQNA?p=preview
Upvotes: 2