Cod*_*er1 215 javascript angularjs angularjs-ng-repeat
我想使用父列表的索引(foos)作为子列表(foos.bars)中函数调用的参数.
我找到了一个帖子,有人建议使用$ parent.$ index,但$index不是属性$parent.
如何访问父级索引ng-repeat?
<div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Cod*_*er1 278
我的示例代码是正确的,问题是我的实际代码中的其他问题.尽管如此,我知道很难找到这方面的例子,所以我正在回答它,以防其他人在寻找.
<div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Sam*_*nen 218
根据ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat,您可以将键或数组索引存储在您选择的变量中.(indexVar, valueVar) in values
所以你可以写
<div ng-repeat="(fIndex, f) in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething(fIndex)">Add Something</a>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
一个级别的上涨仍然是非常干净的$ parent.$ index但几个父母起来,事情可能会变得混乱.
注意:$index将继续在每个范围定义,它不会被替换fIndex.
vuc*_*lur 42
看看我对类似问题的回答.
通过别名$index我们不必写疯狂的东西$parent.$parent.$index.
$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>
Run Code Online (Sandbox Code Playgroud)
Plunker:http://plnkr.co/edit/knwGEnOsAWLhLieKVItS?p = info
| 归档时间: |
|
| 查看次数: |
140275 次 |
| 最近记录: |