簡體   English   中英

如何使用angularjs從表中刪除行

[英]How to delete the row from table using angularjs

我想使用angularjs從表中刪除行。 但是它不能正常工作,它將刪除上一行。 沒有正確的行。 如何糾正這一點。
請查看正在運行的演示

代碼被截斷

<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>

這樣嘗試

視圖

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

控制者

$scope.removeRow = function(index) {
   $scope.tasks.splice(index, 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: 如果您通過ng-click$index傳遞為data-ng-click="removeRow($index)"則只有在您有排序選項的情況下,如果ng-repeat的選項沒有順序,此選項才有效錯誤。 因為在排序時$index與(0,1,2,3)相同,但是數組順序可能已更改(例如:0-index元素可以位於已排序數組的1-index中,因此如果傳遞$ index,則它將刪除實際數組的第一個索引),因此$ index不代表實際數組元素。

排序選項=> orderBy

更新的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM