gpt4 book ai didi

javascript - 如何使用angularjs从表中删除行

转载 作者:行者123 更新时间:2023-11-30 10:01:47 25 4
gpt4 key购买 nike

我想使用 angularjs 从表中删除行。但它不能正常工作,它删除了前一行。不是正确的行。如何纠正这个问题。
请参阅工作 DEMO

代码已截取

<body ng-app="myApp" ng-controller="tasksCtrl">
<div>
<table class="table table-striped">
<tbody>
<tr ng-repeat="task in tasks">
<td>
<a class="btn" data-toggle="modal" data-ng-click="removeRow(task)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>

<script>
var app = angular.module('myApp', []);

app.controller('tasksCtrl', function($scope, $http) {
$http.get("data.json")
//$http.get("/todo/api/v1.0/tasks")
.success(function(response) {
console.log(response.tasks)
$scope.tasks = response.tasks;
});

$scope.removeRow = function(task) {
$scope.tasks.splice(task, 1);
};
});
</script>
</body>

最佳答案

需要获取尝试删除的索引

这样做,

 $scope.removeRow = function(task) {
// get the index
var index = $scope.tasks.indexOf(task);

//delete the element from the array
$scope.tasks.splice(index, 1);
};

PS:如果您通过 ng-click$index 作为 data-ng-click="removeRow($index)" 这仅在 ng-repeat 中没有按选项排序的情况下才有效,如果您有排序选项,那么您的删除就会出错。因为排序时 $index 与 (0,1,2,3) 相同,但数组顺序可能已更改(例如:0-index 元素可以位于已排序数组的 1-index 中,所以如果你传递 $index 那么它会删除实际数组的第一个索引)所以 $index 不代表实际的数组元素。

sorting options => orderBy

UPDATED DEMO

关于javascript - 如何使用angularjs从表中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31260111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com