Frage

I am creating a angular application, which has one li with ng-repeat and a text box for searching the out put in ng-repeat, the repeated item has a delete "X" button which deletes the record from DB. problem i am facing is how to remove searched record from the array using splice.

http://plnkr.co/edit/oPBofD2wL2ZUrD23f8Rr?p=preview

go to above plnkr click on any of the "x" without searching, then it will get removed from the list . but when you search for something lets say ruby then only ruby will come into the list but by clicking on "x" it will still appear . I need help in removing the searched field from the array using array operation, i dont want to regenerate that array again.

War es hilfreich?

Lösung 3

The reason is that you are sending the $index for removing, instead of that pass the id like

 <a href="" ng-click="delete(project.id)">X</a>  

Working Demo

Try this out

$scope.delete = function(idx) {
  for ( var i = 0; i < $scope.projects.length; i++){
    if ($scope.projects[i].id === idx)
     {
         $scope.projects.splice(i, 1);
     }
  }
};

Andere Tipps

instead of just using the index as a parameter, calculate your index with a search of the json element in the array.

Like so:

$scope.delete = function(project) {
  idx = $scope.projects.indexOf(project);
  $scope.projects.splice(idx, 1);
};

DEMO

The problem is that your idx is set to $index. That is the index of the ng-repeat, not the index of the array so when the list is filtered you're now deleting the wrong element. (You'll notice this if you clear the search-box after deleting)

If you change your HTML to

<a href="" ng-click="delete(project)">X</a>

The delete function will receive the actual element that needs to be removed and can be rewritten to

$scope.delete = function(project) {
  $scope.projects.splice($scope.projects.indexOf(project), 1)
};
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top