Drop Shadow
Drop Shadow

Reputation: 808

How to delete an object from angularJs Model?

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 ?

Upvotes: 1

Views: 5795

Answers (3)

rafat
rafat

Reputation: 817

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);               
};

Upvotes: 3

ma08
ma08

Reputation: 3744

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

Upvotes: 1

Nicolai
Nicolai

Reputation: 1953

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>

Upvotes: 4

Related Questions