在我的 angularjs 应用程序中,我有以下对象列表。
$scope.itemsList = [
{
"setupId": "T_2893",
"name" : "abc"
},
{
"setupId": "LBT826",
"name" : "xyz"
},
{
"setupId": "LBT1252",
"name" : "pqr"
},
{
"setupId": "G1252",
"name" : "dwr"
}
]
现在,当我调用 $scope.changeOreder(1, 3) 函数时,它应该根据上一个和下一个索引对对象重新排序。所以列表应该如下。
$scope.itemsList = [
{
"setupId": "T_2893",
"name" : "abc"
},
{
"setupId": "LBT1252",
"name" : "pqr"
},
{
"setupId": "G1252",
"name" : "dwr"
},
{
"setupId": "LBT826",
"name" : "xyz"
}
]
现在,如果我调用 $scope.changeOreder(2, 0)
,新列表应该是,
$scope.itemsList = [
{
"setupId": "G1252",
"name" : "dwr"
},
{
"setupId": "T_2893",
"name" : "abc"
},
{
"setupId": "LBT1252",
"name" : "pqr"
},
{
"setupId": "LBT826",
"name" : "xyz"
}
]
在我的 $scope.changeOrder 函数中,我尝试了不同的方法,例如备份 prevIndex
处的对象,然后删除 prevIndex
处的对象以插入newIndex
处备份的 obj,但因为我已删除该对象,所以 newIndex
在当前列表中不再有效!!!。像这样,我尝试了不同的方法,但最终的列表没有按照我期望的方式排序。谁能帮我解决这个问题吗?
最佳答案
将项目移动到指定索引:
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);
关于javascript - 需要根据 Angular js应用程序中的索引重新排序对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34994671/