Sam
Sam

Reputation: 14596

angularjs: how does $index work in ng-repeat ?

consider the following table :

 <tbody data-ng-repeat="job in jobs">
    <tr>
        <td>{{job.fileName}}</td>  
        <td>
            <button class="btn" ng-click="deleteJob($index);"><i class="icon-delete"></i>&nbsp; delete</button>
        </td>
    </tr>
</tbody>

if I delete a job, the row id is passed to the function and it works just fine.

 scope.deleteJob = function (id) {
                scope.jobs.splice(id, 1);
            }

However if I change deleteJob($index) to deleteJob({{$index}}) then, the index is still passed to the function, however if I delete row 1, the index of row 2 remains 2 and it is not updated.

How come ? What's the difference between the two approaches ?

Upvotes: 4

Views: 1891

Answers (2)

Quad
Quad

Reputation: 1718

It's because when you use $index it's a variable but when you use {{$index}} value used instead of variable.

If you check the DOM you will see that in the first case($index) you still see $index in DOM, but when you use {{$index}} you will see 0,1,2... in the DOM.

If you use {{index}}, when array is changed your DOM will still have have deleteJob(0),deleteJob(2) ... and so on - missing the deleted indices.

if you use $index your DOM will have $index, which is a variable that represents actual current index.

Upvotes: 5

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

I think {{$index}} is wrong aproach and valid usage of iterator offset of the repeated element must be $index.

$index is iterator and after delete one of items should be updated respectively.

When we write {{$index}} means - show current value stored in iterator.

Like in other languages, Java for example, if we run in loop over list (like ng-repeat) we can only use iterator to remove Item to prevent index issues

Demo Fiddle

Upvotes: 1

Related Questions