0

I'm displaying elements from an arraylist in table on the webpage. I want to make sure that once the user press "delete the data", the element in the table is immediately removed so the user does not have to refresh and wait to see the new table. So I'm currently doing it by removing the element from the arraylist, below is the code:

$scope.list= function(Id) {
        var position = $scope.list.indexOf(fooCollection.findElementById({Id:Id}));
        fooCollection.delete({Id:Id});

        if (position>-1) {
            $scope.list.splice(position,1);
        }
        $location.path('/list');
    };

But I the position is always -1, so the last item is always removed from the list no matter which element I delete.

Vineet
  • 4,525
  • 3
  • 23
  • 42
sunny
  • 49
  • 1
  • 1
  • 7

2 Answers2

0

I found it strange you we're operating on two different lists to begin with so I assumed you were taking a copy of the initial list. This enabled me to reproduce your bug. On the following line you're trying to find an object that isn't present in your list.

var position = $scope.list.indexOf(fooCollection.findElementById({Id:Id}));

Eventhough we're talking about the same content, these two objects are not the same because:

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

So there lies your problem. You can see this reproduced on this plunker.

Fixing it the quick way would mean looping over your $scope.list and finding out which element actually has the id that is being passed.

skubski
  • 1,586
  • 2
  • 19
  • 25
-1

you can use the splice method of javascript which takes two paramete

arrayObject.splice(param1, param2);

param1 -> from this index elements will start removing

param2 -> no of elements will be remove

like if you want to remove only first element and your array object is arrayObject then we can write code as following

arrayObject.splice(0, 1);
dom
  • 1,086
  • 11
  • 24