【问题标题】:How to delete the row from table using angularjs如何使用angularjs从表中删除行
【发布时间】:2015-09-24 10:36:14
【问题描述】:

我想使用 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>

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你需要获取尝试删除的索引

    这样做,

     $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 : 如果您将$index 通过ng-click 传递为data-ng-click="removeRow($index)",则只有在ng-repeat 中没有按选项排序时才有效,如果您有排序选项,那么您的删除会出错。因为当排序时$index 与 (0,1,2,3) 相同,但数组顺序可能已更改(例如:0-index 元素可以位于已排序数组的 1-index 中,因此如果您传递 $index那么它将删除实际数组的第一个索引)因此 $index 不代表实际的数组元素。

    排序选项 => orderBy

    UPDATED DEMO

    【讨论】:

    【解决方案2】:

    这样试试

    查看

    <a class="btn" data-toggle="modal" data-ng-click="removeRow($index)">Delete</a>
    

    控制器

    $scope.removeRow = function(index) {
       $scope.tasks.splice(index, 1);
    };
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2018-05-24
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多