Steve
Steve

Reputation: 14912

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. I am using a variable to ng-show that div, and the div that does the hide/show is

<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). 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. 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.

How can I append the index number or something in this case?

Upvotes: 3

Views: 366

Answers (3)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

you don't need to add several variables in ng-repeat. because ng-repeat creates a child scopes in each and every repeat. so the variable creates with in the child scopes, so one variable not visible to the other child scopes in ng-repeat

so,

<div ng-click="myVar1=!myVar1" ng-class="{open : myVar1}" ng-repeat="claim in claims">
{{  claim }}
</div>

this would be enough.

here is the Plunker

Upvotes: 2

SoluableNonagon
SoluableNonagon

Reputation: 11755

If you need to toggle visibility on a repeated div, you can do as such:

<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). Then ng-click will toggle that isOpen variable. Then ng-class will watch for changes on that variable.

Upvotes: 3

Jochen van Wylick
Jochen van Wylick

Reputation: 5401

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. You could use that to generate unique class ids.

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. Since you youse claim in claims you can set the variable on claim as you were doing before.

Upvotes: 3

Related Questions