If you're looking to manage the state of an accordion in your Angular application, there are a couple of approaches you can take. One option is to utilize an angular Service to store the accordion's state, or you could simply place it into $rootScope
for a quick solution.
Within your angular module's run function:
app.run(function($rootScope) {
// Set your default state here: true for open, false for closed
$rootScope.accordionOpen = true;
});
In your HTML:
<accordion-group heading="Main Information" is-open="accordionOpen">
This will maintain the state across different routes, but not after a browser refresh. If you want to persist the state even after a refresh, adjust your module's run function as follows:
app.run(function($rootScope) {
// Set your default state here: true for open, false for closed
localStorage.accordionOpen = localStorage.accordionOpen || true
$rootScope.accordionOpen = Boolean(localStorage.accordionOpen);
$rootScope.toggleAccordion = function() {
localStorage.accordionOpen = !Boolean(localStorage.accordionOpen);
});
});
And in your HTML:
<accordion-group heading="Main Information" ng-click="toggleAccordion()" is-open="accordionOpen">
If you'd like the state to be cleared when the browser tab is closed, change localStorage
to sessionStorage
. It's important to use Boolean()
because localstorage can only handle data of type String
.