对ul中的列表项使用ng-repeat重复employeePayments数组中的项目,通过$ stateParams访问并存储在$ scope.employeePayments中。
每当我点击某个项目的删除按钮时,根据我尝试设置拼接功能的两种方式,它会删除数组中的第一个项目或最后一个项目,而不是删除所选的项目通过数组中的索引查找它。
第一种方法 - 始终删除第一项:
$scope.deleteEmployeePaymentRow = function(employeePayment) {
$scope.employeePayments.splice(employeePayment, 1);
}
第二种方法 - 始终删除最后一项:
$scope.deleteEmployeePaymentRow = function(employeePayment) {
var index = $scope.employeePayments.indexOf(employeePayment);
$scope.employeePayments.splice(index, 1);
}
-
ng-repeat HTML:
<tr data-ng-repeat="employeePayment in employeePayments">
<td>{{employeePayment.code}}</td>
<td>{{employeePayment.paymentType}}</td>
等...
-
删除按钮HTML:
<a data-ng-click="deleteEmployeePaymentRow(employeePayment)">Delete Payment</a>
答案 0 :(得分:4)
您可以使用$ index,
直接从ng-repeat传递索引<a data-ng-click="deleteEmployeePaymentRow($index)">Delete Payment</a>
然后在删除方法中,试试这个
$scope.deleteEmployeePaymentRow = function(index) {
$scope.employeePayments.splice(index, 1);
}
答案 1 :(得分:0)
第一个方法删除了第一个项目,因为您将splice
一个对象作为第一个方法传递,而它应该是一个数字。
第二种方法可以完成它的工作,因为$scope.employeePayments.indexOf(employeePayment)
无法在数组中找到employeePayment
。在这种情况下,indexOf
将返回-1,该splice将其解释为“删除最后一个元素”。
在第二种方法的console.log中可能值得一推,看看为什么indexOf
无法找到你的对象。
答案 2 :(得分:0)
尝试删除使用索引编辑您的按钮: -
<a ng-click="deleteEmployeePaymentRow($index)">Delete Payment</a>
并在控制器中
$scope.deleteEmployeePaymentRow = function(index) {
// first check if its correct row deleting LOG it
var deleteRow = $scope.employeePayments[index];
console.log(deleteRow);
}
如果要从数组中删除正确的行:
$scope.deleteEmployeePaymentRow = function(index) {
// first check if its correct row deleting LOG it
var deleteRow = $scope.employeePayments[index];
console.log(deleteRow);
$scope.employeePayments.splice(index, 1);
}
如果您只想让索引元素不再存在,但您不希望其他元素的索引发生变化:
$scope.deleteEmployeePaymentRow = function(index) {
// first check if its correct row deleting LOG it
var deleteRow = $scope.employeePayments[index];
console.log(deleteRow);
delete $scope.employeePayments[index];
}