1

I want to delete the row from table using angularjs. But it is not working properly, It delete the previous row. Not the correct row. How to rectify this.
Please see the working DEMO

Code snipped

<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>
geeks
  • 2,025
  • 6
  • 31
  • 49

2 Answers2

2

Try like this

View

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

Controller

$scope.removeRow = function(index) {
   $scope.tasks.splice(index, 1);
};
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • If you find this question is sencefull then please upvote it – geeks Jul 07 '15 at 05:19
  • @AnikIslamAbhicould you suggest any tutorial on this.. I have one more problem please see there is bounty on this question http://stackoverflow.com/questions/31207250/how-to-allow-users-to-login-protected-flask-rest-api-in-angularjs – geeks Jul 07 '15 at 05:24
2

You need to get the index of trying to delete

to do that,

 $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 : if you pass the $index through ng-click as data-ng-click="removeRow($index)" this will work only if there is no order by options in ng-repeat if you have sorting options then your deletion gets wrong. because when sorting is there $index is same as the (0,1,2,3) but array order may have changed (ex: 0-index element can lay in 1-index of sorted array so if you pass the $index then it will delete the 1st index of actual array) so $index not represent the actual array element.

sorting options => orderBy

UPDATED DEMO

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
  • could you suggest any tutorial on this.. I have one more problem please see there is bounty on this question http://stackoverflow.com/questions/31207250/how-to-allow-users-to-login-protected-flask-rest-api-in-angularjs – geeks Jul 07 '15 at 05:23