简体   繁体   中英

How to delete elements from array in Angularjs application

I am trying to do a basic task: removing an item from my array.
The array looks like that:

myWordsInJSON = [{"eng":"frau","rus":"жена"},{"eng":"mann","rus":"муж"},{"eng":"witwe","rus":"вдова"},{"eng":"witwer","rus":"вдовец"},{"eng":"schwiegervater","rus":"свекор"}]

Here is my html code:

<tr ng-repeat="item in myWordsInJSON">
          <td>{{$index + 1}}</td>
          <td>{{item[Params.lang1]}}</td>
          <td>{{item[Params.lang2]}}</td>
          <td><span class="label label-danger"
                         ng-click="cut({{$index}})">x</span>
          </td>
        </tr>

Output screenshot

It looks great. When I press the 'delete' label, my Controller's cutting function starts:

 $scope.cut = function(index){
  $scope.myWordsInJSON.splice(index,1);
  if ($scope.myWordsInJSON.length == 1)
    $scope.myWordsInJSON = [];
  console.log('cuted, index =', index,$scope.myWordsInJSON);
};

But than strange things happens. After cutting a few items from the beginning of my array, I've got this picture:

everythig looks ok

DOM looks great, last element of my array is:

<tr ng-repeat="item in myWordsInJSON" class="ng-scope">
          <td class="ng-pristine ng-untouched ng-valid ng-binding">2</td>
          <td class="ng-binding">schwiegervater</td>
          <td class="ng-binding">свекор</td>
          <td><span class="label label-danger" ng-click="cut(1)">x</span>
          </td>
        </tr>

BUT!!! When I am pressing on this element, which has to invoke my cut function like cut(1) , nothing happens and in my console I see

index = 4

that means that my function is getting index=4 instead of index=1

So, it looks like my indexes from initial page compilation is still here... How can I solve this problem?

Update!

The problem solved by using '$index' instead of '{{$index}}'. Sanks to valverde93 . But I still cant understand why that happens ))) Maby someone can explane?

I've encountered the same issue in my current project. The problem was that the index of the the repeated elements and the actual index of the object in that array are different.

To solve the issue I had to pass the ID of the object like this
ng-click="deleteForId(repeatedElement.id)
and then, in the deleteForId function, I search for that object in the array and get its index. Only then I call
$scope.myObj.splice(index, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM