4

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 ?

1
  • Can you setup a plunker? Commented Oct 14, 2013 at 12:21

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.