pr.nizar
pr.nizar

Reputation: 651

AngularJS: $index lost with filter?

I'm new to AngularJS so please be kind to me.. :-P

So I'm looping twice with ng-repeat as in this example:

    <ul>
      <li ng-repeat="b in aMSG">
        <p>{{b.name}}</p>
        <ul>
          <li ng-repeat="c in b.x"><a ng-click="getM($parent.$index,$index)" href="#">{{c.name}}</a></i>
        </ul>
      </li>
    </ul>

See the fiddle: http://jsfiddle.net/trK98/

But when I apply a filter to search for text within the children:

    <ul>
      <li ng-repeat="b in aMSG">
        <p>{{b.name}}</p>
        <input type="text" ng-model="search" placeholder="Search for?">
        <ul>
          <li ng-repeat="c in b.x|filter:search"><a ng-click="getM($parent.$index,$index)" href="#">{{c.name}}</a></i>
        </ul>
      </li>
    </ul>

The $index is lost as you can see here: http://jsfiddle.net/zb2kc/

(search for instance for juice then click on it you'll see $index = 0)

What am I doing wrong?

Thank you!

P.S: Sorry for my poor english.

Upvotes: 0

Views: 450

Answers (1)

user680786
user680786

Reputation:

Never use $index for any kind of logic. It can be used for managing CSS classes only. It's a highly volatile variable and will be changed after any change in source array (deletion, re-ordering), so $index is not bind to element of array, but only to position of some element in current view rendering.

Upvotes: 2

Related Questions