The Problem:

Welcome to “Continuous Improvement,” the podcast where we explore solutions to common programming problems and help you become a better developer. I’m your host, Victor. In today’s episode, we’ll be discussing a problem I recently encountered with the accordion directive in Angular UI Bootstrap and the solution I found to make it work with dynamic content. So let’s dive in!

The problem arose when I was using the accordion directive in Angular UI Bootstrap version 0.1.2. On the demo page, you can see an example where the first accordion group is opened by default:

<accordion-group heading="First Header" is-open="true"> </accordion-group>

This worked perfectly fine for static content. However, when I tried to generate dynamic content using ng-repeat, it didn’t behave as expected. The accordion didn’t open as intended. Let me show you an example:

<accordion-group heading="" ng-repeat="group in groups" is-open="true"> </accordion-group>

But don’t worry, I’ve found a solution to this problem!

Instead of using a static value for is-open, we can bind it to a property in our controller. Here’s what the updated template looks like:

<accordion-group heading="" ng-repeat="group in groups" is-open="status.isItemOpen[$index]"> </accordion-group>

And in the controller, we define the groups and the status object which will hold the isItemOpen property:

$scope.groups = ['First Header', 'Second Header', 'Third Header'];
$scope.status = { isItemOpen: new Array($scope.groups.length), isFirstDisabled: false };
$scope.status.isItemOpen[0] = true;

By using $index, we can dynamically set the value of isItemOpen for each accordion group based on their index. In this example, the first accordion group will be opened by default.

[BREAK]

If you prefer the first accordion group to be closed by default, simply change the value of true to false in the last line of the code snippet.

So, with this solution, you can now have dynamic content in your accordion groups and control their initial state using the is-open property.

And that’s a wrap for today’s episode of “Continuous Improvement.” I hope this solution helps you overcome the problem with the accordion directive in Angular UI Bootstrap. If you have any questions or need further clarification, feel free to reach out to me. Thanks for listening, and until next time, happy coding!