1

I am trying to write a function that enables me to remove an item when the button is clicked. My ng-repeat is below :

<tr ng-repeat="x in myData.List">
            <td>{{x.name}}</td>
            <td>{{x.item}}</td>                
            <td><button type="submit" ng-click="delete(x.id)" class="button">Remove</button></td>
        </tr>

and my delete function is :

$scope.delete = function (id) {            
     var index = $scope.myData.List.indexOf(id);
     $scope.myData.List.splice(index,1);               
};

But problem is that it delete the last object. But I want delete a particular item. what should I do ?

1
  • can you provide your myData it is array of objects or simple array ? Commented Feb 19, 2015 at 11:56

3 Answers 3

4

You should use x instead of its id in .indexOf:

$scope.delete = function (x) {            
     var index = $scope.myData.List.indexOf(x);
     $scope.myData.List.splice(index,1);               
};

and

<button type="submit" ng-click="delete(x)" class="button">Remove</button>
Sign up to request clarification or add additional context in comments.

2 Comments

Its working but I need the id's value also . so how can i get that ?
@DropShadow, use x.id, i.e function(x){ console.log(x.id)}.
3

This in not a angular specific problem. Array Splice is related JavaScript array manipulation. Pass only the index x instead of x.id. So your html code will be..

<td><button type="submit" ng-click="delete(x)" class="button">Remove</button></td>

$scope.delete = function (x) {            
     var index = $scope.myData.List.indexOf(x);
     $scope.myData.List.splice(index,1);               
};

Comments

1

The problem is your myData.List is a collection of objects not ids. You need to search for the id

$scope.delete = function (id) {            
  var index=-1;
  for(;index<$scope.myData.List.length;index++){
   if($scope.myData.List.id===id)
     break;
  }
  if(index!==-1){
   $scope.myData.List.splice(index,1);               
  }
}

Or you can pass the object to the function as Nicolai posted

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.