ajmajmajma
ajmajmajma

Reputation: 14216

Individual toggles inside an ng-repeat

I have some content coming in which I am running through a repeat, each one of these content items has to have a toggle open/close functionality to it. I figured my best bet in marking them individually is using something like the $index of the item in the repeat. I am just using a (bootstrap) class to show/hide like so :

     <a ng-click="{{$index}}inner = !{{$index}}inner" >{{item.node.id}}</a>
     <div class="nested " ng-class="{'collapse' : !{{$index}}inner">

So - a click toggle on the a above. This does not work because of the syntax, but what I'm wondering here is if there is a nice elegant solution to this problem. This way I tried first seems a little messy. Thanks!

Upvotes: 0

Views: 1450

Answers (3)

ryanyuyu
ryanyuyu

Reputation: 6486

I like adding properties to the actual objects themselves. Then, within your ng-repeat, you can just reference the individual object (instead of trying to re-index into the array) and apply all logic as you need.

Maybe something like this:

<div ng-repeat="item in array">
 <a ng-click="item.collapsed = !item.collapsed" >{{item.node.id}}</a>
 <div class="nested " ng-class="{'collapse' : item.collapsed"></div>

</div>

Upvotes: 2

Mark Polak
Mark Polak

Reputation: 403

The ng-repeat directive created a scope for each of the elements. Therefore you could just use the ng-click to toggle a property on that scope.

Also the syntax of your ng-class is not totally correct.

For working example see http://jsbin.com/yuyucojeco/edit?html,js,output

Upvotes: 3

Jax
Jax

Reputation: 1843

I have implemented smt similar inside an ng-repeat using bootstrap as well like so: here is the button:

<a data-toggle="collapse" data-target="#{{item.id}}" class="accordion-toggle btn btn-xs btn-success"></a>

then the collapsible tab:

<div class="accordion-body collapse" id="{{item.id}}"> <!-- accordion starts -->
    <!-- some content here -->  
</div> <!-- accordion ends -->

Upvotes: 1

Related Questions