简体   繁体   中英

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 ?

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.

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

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