【发布时间】:2015-01-03 04:16:58
【问题描述】:
我有以下对象数组。
[{"name":"Rain"},{"name":"Storm"},{"name":"Forest"}]
其中有索引[0, 1, 2]。
我正在尝试使用代码删除给定位置上的项目:
$scope.selectedSounds.splice(index, 1);
但它以错误的方式删除项目,例如无法删除最后一个项目。如果我试图删除索引为 1 的项目,它会删除索引为 2 的项目..
请问有什么问题?
两种方法我都试过了:
$scope.removeSoundFromSelection = function(index) {
try {
// First
$scope.selectedSounds.splice(index, 1);
var indexNew = $scope.selectedSounds.indexOf(index);
console.log(indexNew);
if (indexNew > -1) {
$scope.selectedSounds.splice(indexNew, 1);
}
// Second
if ($scope.selectedSounds.hasOwnProperty(index)){
delete $scope.selectedSounds[index];
}
//delete $scope.selectedSounds[index];
} catch(e) {
$scope.showAlert();
}
};
添加模板:
<div class="list">
<a class="item item-thumbnail-left" ng-repeat="sound in selectedSounds">
<img src="cover.jpg">
<h2>{{sound.name}}</h2>
<p>TEST</p>
<div class="customDeleteBtnInList">
<button ng-click="removeSoundFromSelection({{$index}})" class="button button-icon icon ion-close-circled"></button>
</div>
</a>
</div>
【问题讨论】:
-
它不是删除错误的项目,它只是在目标项目被删除后移动项目。所以现在可以在索引 1 处找到索引 2 处的项目
-
你能告诉我们更多代码吗?你如何找到索引,你是否在循环中调用 splice?
-
我更新了我的问题。
-
那些条件是什么
if (indexNew > -1) {为什么需要它?你为什么要拼接它然后deleteing 呢?告诉我们你是如何传递索引的?如果您使用 ng-repeat 并传递 $index,您只需要$scope.selectedSounds.splice(index, 1);。 -
角度 schmangular。 myArray.splice(0,1) 实际上删除最初位于索引 1 处的元素而不是最初位于索引 0 处的元素的底层纯 JavaScript 原因是什么?
标签: javascript arrays angularjs angularjs-scope angularjs-ng-repeat