Reputation: 2055
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>
Upvotes: 1
Views: 3023
Reputation: 21901
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
Upvotes: 2
Reputation: 25352
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);
};
Upvotes: 2