realph
realph

Reputation: 4671

Angular JS: Toggle Only One Item at a Time

So I've got an list of names that I'm doing an ng-repeat on, and I've got an ng-click on each name, that when clicked, reveals a tooltip. I'm doing this like so:

<li ng-repeat="person in names" ng-click="tooltip = !tooltip">
  <span>{{ person }}</span>
  <div class="tooltip" ng-show="tooltip">This is {{ person }}'s tooltip</div>
</li>

When you click on a person 1's name their tooltip appears, but when you click on person 2, their tooltip also appears. I would like only one tooltip to appear at once. Is this possible using the toggle technique tooltip = !tooltip above?

I've set up a JS Bin of my issue, here: https://jsbin.com/faxoviwuze/1/edit?html,js,output

Any help is appreciated.

Thanks in advance!

Upvotes: 2

Views: 541

Answers (1)

vp_arth
vp_arth

Reputation: 14982

Use the $index:

<ul ng-init="model.tooltip=-1">
<li ng-repeat="person in names" ng-click="model.tooltip = $index">
  <span>{{ person }}</span>
  <div class="tooltip" ng-show="model.tooltip==$index">This is {{ person }}'s tooltip</div>
</li>
</ul>

I recommend to not use scalar scope variables like tooltip.
It's easy to unbind. Use something like model.tooltip.

Simple fiddle


Also, there is not a reason for $scope injecting - you can to use controllerAs syntax.

JSBin

Upvotes: 3

Related Questions