[英]iterate a variable in an Angular JS repeater?
I have a setup where a div hides and shows the following div, to create a collapsing div. 我有一个div隐藏并显示以下div的设置,以创建一个折叠div。 I am using a variable to ng-show that div, and the div that does the hide/show is 我使用变量来表示div,以及执行hide / show的div是
<div ng-click="costSummary=!costSummary" ng-class="{open : costSummary}">
Clicking the div toggles the variable and the class (to style a header inside, for a disclosure triangle). 单击div切换变量和类(为内部标题设置样式,对于显示三角形)。 Works fine. 工作正常。
However, I need to use this construct in an ng-repeat, and I'm not sure how I can increment that variable so each iteration has a unique class. 但是,我需要在ng-repeat中使用这个构造,我不知道如何增加该变量,因此每次迭代都有一个唯一的类。 As in: 如:
<div ng-click="myVar1=!myVar1" ng-class="{open : myVar1}" ng-repeat="claim in claims">
since this hide/show requires each header/div pair to have a unique class name. 因为这个hide / show要求每个header / div对都有一个唯一的类名。
How can I append the index number or something in this case? 在这种情况下,如何附加索引号或其他内容?
Inside an ng-repeat, you have access to $index
- which will give you the index of the current item in the collection you are iterating over. 在ng-repeat中,您可以访问$index
- 这将为您提供正在迭代的集合中当前项的索引。 You could use that to generate unique class ids. 您可以使用它来生成唯一的类ID。
But, could you not also try this: 但是,你能不能尝试这个:
<div ng-repeat="claim in claims">
<div ng-click="claim.myVar1=!claim.myVar1" ng-class="{open : claim.myVar1}">
</div>
</div>
You place the div with ng-click inside an ng-repeater wrapper. 您可以在ng-repeater包装器内部使用ng-click放置div。 Since you youse claim in claims
you can set the variable on claim as you were doing before. 由于您claim in claims
您可以按照以前的方式设置claim in claims
变量。
If you need to toggle visibility on a repeated div, you can do as such: 如果您需要在重复的div上切换可见性,您可以这样做:
<div ng-click="claim.isOpen=!claim.isOpen" ng-class="{open : claim.isOpen}" ng-repeat="claim in claims" ng-init="claim.isOpen = false">
Explanation: 说明:
ng-init will initialize an "isOpen" variable on each repeated claim (This should really be done on the JS end instead). ng-init将在每个重复的声明中初始化一个“isOpen”变量(这应该在JS端完成)。 Then ng-click will toggle that isOpen variable. 然后ng-click将切换isOpen变量。 Then ng-class will watch for changes on that variable. 然后ng-class将监视该变量的变化。
you don't need to add several variables in ng-repeat
. 你不需要在ng-repeat
添加几个变量。 because ng-repeat
creates a child scopes in each and every repeat. 因为ng-repeat
在每次ng-repeat
都会创建一个子范围。 so the variable creates with in the child scopes, so one variable not visible to the other child scopes in ng-repeat
因此变量在子范围中创建,因此一个变量对于其他子范围在ng-repeat
不可见
so, 所以,
<div ng-click="myVar1=!myVar1" ng-class="{open : myVar1}" ng-repeat="claim in claims">
{{ claim }}
</div>
this would be enough. 这就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.