ng-repeat dynamic variable name

2019-06-28 00:24发布

I am implementing ng-repeat to create elements for a bootstrap accordion interface.

I have ng-repeat working however the issue I have is that I need to dynamically create the ID in order to target the accordion element individually.

My ng-repeat HTML block references:

<div class="panel-heading" data-toggle="collapse" data-parent="#products-accordion" href="#collapseOne">

And lower down references:

<div id="collapseOne" class="panel-collapse collapse in">

For this to work correctly, collapseOne needs to be dynamic - collapse1, collapse2 etc. How is it possible to iterate values in ng-repeat? "collapse" + i basically is what Im trying to achieve.

Secondly, only the first item in the ng-repeat list requires the "in" class on this line:

<div id="collapseOne" class="panel-collapse collapse in">

This ensures the first item is opened.

Thanks in advance for your help

1条回答
够拽才男人
2楼-- · 2019-06-28 00:47

You could use ng-repeats built-in $index. (Documentation here: https://docs.angularjs.org/api/ng/directive/ngRepeat)

So it would look like this:

<div id="collapse_{{ $index }}" class="panel-collapse collapse in">

Which would create:

<div id="collapse_0" class="panel-collapse collapse in">
<div id="collapse_1" class="panel-collapse collapse in">

Etcetera.

For opening the first div by default I think you can use ng-class like this:

<div id="collapse_{{ $index }}" ng-class="{ in : $index == 0 }" class="panel-collapse collapse">
查看更多
登录 后发表回答