0

I have nested array so I had to use 3 times ng-repeat

    <div ng-repeat = "cat in cats"  >

          <div ng-repeat = "kitty in cat  "  >

             <button ng-click="delete($index)">Delete</button>

      </div>
   </div>
 </div>

So my problem is that I can't get access to 2nd ng-repeat $index , any ideas ?

2 Answers 2

4

This is the purpose of the ng-init directive

<div ng-repeat="cat in cats" ng-init="catIndex = $index">
   <div ng-repeat="kitty in cat">
        <button ng-click="delete(catIndex)">Delete</button>
   </div>
</div>

Alternatively use (index, value) formatting:

<div ng-repeat="(catIndex, cat) in cats">
   <div ng-repeat="kitty in cat">
        <button ng-click="delete(catIndex)">Delete</button>
   </div>
</div>
4
  • or you could have used the (key, value) ng-repeat syntax?
    – ryeballar
    Commented Jul 30, 2014 at 16:24
  • @ryeballar - that's for objects, not arrays
    – Alex
    Commented Jul 31, 2014 at 8:01
  • 2
    You're wrong, it works for arrays as well. If the element being iterated in an ng-repeat is an array then the key is the index. Thus, you can do it like this, ng-repeat="(catIndex, cat) in cats"
    – ryeballar
    Commented Jul 31, 2014 at 8:04
  • You can add an update to your answer, at least the OP is aware of his options, you answer is correct but it adds N more times the watchers.
    – ryeballar
    Commented Jul 31, 2014 at 12:30
-2
<div ng-repeat = "cat in cats track by $catIndex"  >

          <div ng-repeat = "kitty in cat track by $kittyIndex "  >

             <button ng-click="delete($kittyIndex)">Delete</button>

      </div>
</div>
1
  • track by has nothing to do with $index
    – Alex
    Commented Jul 30, 2014 at 16:13

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.