Steffen Brueckner Steffen Brueckner - 1 month ago 7
AngularJS Question

use dynamic array key in Angular JS ng-repeat

I am trying to use a specific Array key's ("currenttank") objects ("targets"). The directive-part looks like that:

<tr ng-repeat="item in tanks[{{currenttank}}].targets">
<td ng-bind="item.time"></td>
<td ng-bind="item.target"></td>
<td></td>
<td></td>
</tr>


The following syntax error occurs:


https://docs.angularjs.org/error/$parse/syntax?p0=%7B&p1=invalid%20key&p2=8&p3=tanks%5B%7B%7Bcurrenttank%7D%7D%5D.targets&p4=%7Bcurrenttank%7D%7D%5D.targets%20at%20Error%20(native)


I do not understand how to use the dynamic key within the directive. I have always used the variables within curled braces but that doesn't seem to work here.

Thanks a lot for any help.
Steffen

Answer

You don't have to use {{}} sytax if this expression. Also you may want to wrap it all into ng-if to prevent from rendering if some data isn't set initially. As Ng-if has high priority, It'll prevent code from executing until you want.

<tr ng-repeat="item in tanks[currenttank].targets">
    <td ng-bind="item.time"></td>
    <td ng-bind="item.target"></td>
    <td></td>
    <td></td>
</tr>