I'm currently working on a simple task: removing an item from my array.
The array is structured as follows:
myWordsInJSON = [{"eng":"frau","rus":"жена"},{"eng":"mann","rus":"муж"},{"eng":"witwe","rus":"вдова"},{"eng":"witwer","rus":"вдовец"},{"eng":"schwiegervater","rus":"свекор"}]
Below is the HTML code I am using:
<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>
See output screenshot
Everything looks fine. However, when I click the 'delete' label, the cutting function in my Controller is triggered:
$scope.cut = function(index){
$scope.myWordsInJSON.splice(index,1);
if ($scope.myWordsInJSON.length == 1)
$scope.myWordsInJSON = [];
console.log('cut, index =', index,$scope.myWordsInJSON);
};
But then something strange happens. After deleting a few items from the beginning of my array, I encounter this issue:
everything appears to be normal
The DOM still looks good, with the last element of my array displayed as:
<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>
HOWEVER!!! When I try to click on this element, which should trigger my cut function like cut(1), nothing happens and in the console I see
index = 4
This means that, instead of receiving index=1, my function is getting index=4
It seems like the initial page indexes are still present... How can I resolve this issue?
Update!
The problem was resolved by using '$index' instead of '{{$index}}'. Thanks to valverde93. But I still cannot understand why this occurred))) Perhaps someone can explain?