# How to get a “popover” to close automatically when another one is opened in the same “ng-repeat”

In a recent project, we had a list of items that had to provide additional information when clicked. We decided to use popovers, that allow the selection of content by the user.

## The problem

Popovers work by popping up when a trigger item is clicked, and disappearing with a second click on the item. But in our case, we were using an ng-repeat directive to generate a list of items. Naturally, users would expect any given popover to close automatically when another one is opened. Unfortunately, such popover behaviour is not automatic.

Here is our HTML code, showing an ng-repeat directive generating various items, each with its own popover. As you can see, users will end up with several popovers open at the same time if they don’t take the trouble to click a second time on each trigger item.


{{item.id}}

{{item.name}}

<div class="form-group">
{{item.description}}
</div>



## The solution

### 1. In the controller:

— Add a Boolean array of the same size as the list of items.

— Before opening any popovers, set to “false” all array values.

— Set the array value of our item to “true”.

vm.myPopover = {

isOpen: [],

open: function isOpen(i) {
if (vm.items.length > 0) {
vm.myPopover.isOpen = fillArrayWith(vm.items.length, false);
}
vm.myPopover.isOpen[i] = true;
}
};

function fillArrayWith(n, value) {
var arr = Array.apply(null, Array(n));
return arr.map(function () {
return value;
});
}

### 2. In HTML:

Use the popover-is-open attribute and the ng-click directive:

popover-is-open: looks at the Boolean value of each item to know whether its popover should be opened.

ng-click: calls the Javascript function myPopover.open(\$index), defined in the controller.

The following HTML line:

therefore becomes:

## The Demo

Plunker demo: https://plnkr.co/edit/HYyjg1CpGTbx8eCOPuRb.

Git project: https://github.com/zm2014/popoverClosePrevious.

Discover our
success stories.

A software development project?