删除整个表行 angularjs 按钮



>我有一个包含一些示例数据的表格。 我有一个要在表格行中使用的按钮,单击该按钮将删除整个表格行。 问题是我编码的内容将从表格行中删除内容并保留按钮和表格行。 或者它将删除最后一个表格行,而不是单击按钮的行。

这是我所拥有的:

控制器:

    $scope.removeRow = function (product) {
    var index = -1;
    var productArray = eval($scope.products);
    for (var i = 0; i < productArray.legnth; i++) {
        if (productArray[i].productName == product.productName) {
            index = i;
        console.log(productArray[i].productName);
        }
    }
    if (index === -1) {
        alert("something broke");
    }
    $scope.products.splice(index, 1);
}

.html

 <table class="table table-bordered table-hover">
                    <tr>
                        <!--<th><button class="btn btn-primary" type="button" data-ng-click="showImage = !showImage">{{showImage ? "Hide" : "Show"}} Image</button></th>-->
                        <th>Show or Hide </th>
                        <th>Product</th>
                        <th>Code</th>
                        <th>Avaiable</th>
                        <th>Price</th>
                    </tr>
                    <tr data-ng-repeat="product in products">
                        <td><input type="button" class="btn btn-primary" value="Hide" data-ng-click="removeRow(product)"/></td>
                        <td>{{product.productName}}</td>
                        <td>{{product.productCode}}</td>
                        <td>{{product.releaseDate}}</td>
                        <td>{{product.price | currency}}</td>
                    </tr>
                </table>

您可以在模板中使用$index,例如获取产品数组的索引。

<td><input type="button" data-ng-click="removeRow($index)"/></td>

然后在控制器中,执行以下操作:

$scope.removeRow = function (idx) {
  $scope.products.splice(idx, 1);
};

查看这个潜在的解决方案/正确的语法/策略:http://plnkr.co/edit/Z3NTKo?p=preview

您可以考虑从ng-repeat中获取产品索引,这将使您的代码更简单,并且应该可以工作:

<table class="table table-bordered table-hover">
    <tr>
        <th>Show or Hide </th>
        <th>Product</th>
        <th>Code</th>
        <th>Avaiable</th>
        <th>Price</th>
    </tr>
    <tr data-ng-repeat="(productIndex, product) in products">
        <td><input type="button" class="btn btn-primary" value="Hide" data-ng-click="removeRow(productIndex)"/></td>
        <td>{{product.productName}}</td>
        <td>{{product.productCode}}</td>
        <td>{{product.releaseDate}}</td>
        <td>{{product.price | currency}}</td>
    </tr>
</table>

$scope.removeRow = function (productIndex) {
    $scope.products.splice(productIndex, 1);
}

你得到的两个答案是正确的,至少在他们描述的场景中是正确的。

但是我在使用这些实现时遇到了问题。这是因为如果使用 ng-init="rowIndex = $index" 删除行,则 angular 不会更新其他元素的行号。我使用它是因为删除按钮位于内部 ng 重复循环上。因此,如果删除第 0 行,则第 1 行应变为第 0 行,但保留为第 1 行,因此当您尝试删除第 0 行时,您实际上是在删除第 1 行。您可以使用 ng-repeat 指令上的track by $index来解决此问题。

<tr data-ng-repeat="(productIndex, product) in products track by $index">

最新更新