在嵌套ng-repeat中传递2个$index值

所以我有一个ng-repeat嵌套在另一个ng-repeat中,以构建一个导航菜单。在内部ng-repeat循环的每个<li>上,我设置了一个ng-click,它通过传入$index来调用该菜单项的相关控制器,以让应用程序知道我们需要哪个。然而,我还需要从外部ng-repeat传递$index,以便应用程序知道我们在哪个部分以及哪个教程。

<ul ng-repeat="section in sections">
<li  class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($index)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>

这是一个普伦克http://plnkr.co/edit/bJUhI9oGEQIql9tahIJN?p=preview

191196 次浏览

每个ng-repeat都会用传递的数据创建一个子作用域,并在该作用域中添加一个额外的$index变量。

所以你需要做的是到达父作用域,并使用$index

看到http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview

<li class="tutorial_title \{\{tutorial.active}}" ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials">
\{\{tutorial.name}}
</li>

在处理对象时,您希望尽可能方便地忽略简单的id。

如果你把点击线改为这样,我认为你会很好地走上你的道路:

<li class="tutorial_title \{\{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">

另外,我觉得你可能需要改变一下

class="tutorial_title \{\{tutorial.active}}"

比如

ng-class="tutorial_title \{\{tutorial.active}}"

查看http://docs.angularjs.org/misc/faq并查找ng-class。

$parent.$index更优雅的解决方案是使用ng-init:

<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
<li  class="section_title \{\{section.active}}" >
\{\{section.name}}
</li>
<ul>
<li class="tutorial_title \{\{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
\{\{tutorial.name}}
</li>
</ul>
</ul>

砰砰作响:http://plnkr.co/edit/knwGEnOsAWLhLieKVItS?p=info

只是为了帮助来到这里的人…你不应该使用$parent。$index,因为它并不安全。如果在循环中添加ng-if,就会弄乱$index !

正确的方式

  <table>
<tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
<td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">


<b ng-if="rowIndex == columnIndex">[\{\{rowIndex}} - \{\{columnIndex}}]</b>
<small ng-if="rowIndex != columnIndex">[\{\{rowIndex}} - \{\{columnIndex}}]</small>


</td>
</tr>
</table>

检查:plnkr.co / 52 oihlfexxi9zayntuaj

使用这个语法怎么样(在砰砰作响中查看)。我刚刚发现了这个,非常棒。

ng-repeat="(key,value) in data"

例子:

<div ng-repeat="(indexX,object) in data">
<div ng-repeat="(indexY,value) in object">
\{\{indexX}} - \{\{indexY}} - \{\{value}}
</div>
</div>

使用此语法,您可以将自己的名称赋给$index并区分两个索引。

只需使用ng-repeat="(sectionIndex, section) in sections"即可

这将用于下一层,向下重复。

<ul ng-repeat="(sectionIndex, section) in sections">
<li  class="section_title \{\{section.active}}" >
\{\{section.name}}
</li>
<ul>
<li ng-repeat="tutorial in section.tutorials">
\{\{tutorial.name}}, Your section index is \{\{sectionIndex}}
</li>
</ul>
</ul>