0

Angular UI Bootstrap: Make accordion save state

How can I make the accordion in Angular UI Boot strap save its state?

The behaviour I'd like is when a user clicks on a link inside the accordion, then later clicks back, the same groups are expanded as before.

If it helps, I'm using an SPA with ui-router, and I'm happy to save the state it a cookie.

I've not got very far because I haven't figured out how to read the accordion's state, let alone save it.

tpie
  • 6,021
  • 3
  • 22
  • 41

1 Answers1

0

Plunker

I added a status property to hold the state of the accordion elements

{
  title: 'Dynamic Group Header - 1',
  content: 'Dynamic Group Body - 1',
  status: true
}

Set the directive to track the state of the accordion with is-open="group.status":

<accordion close-others="oneAtATime">
  <accordion-group heading="{{group.title}}" ng-repeat="group in groups" is-open="group.status">
  {{group.content}}
  </accordion-group>
</accordion>

I built a service to keep the accordion data in:

app.factory('accordionKeeper', function() {
  var accordionState = {};
    return {
      get: function() {
        return accordionState;
      },
      set: function(stateObj) {
        accordionState = stateObj;
      }
    }
});

I set a watch on the dataset which the accordion is built from, and if the data changes, save the value in the service:

  $scope.$watchGroup(function() {
    return $scope.groups;
  }, function(newVal, oldVal) {
    if (newVal !== oldVal) {
      accordionKeeper.set($scope.groups)
      console.log('Accordion changed.  Value set')
    }
  });

Now if if you ever need to set the accordion to the saved state, just assign $scope.groups = accordionKeeper.get();

In the plunker I added some buttons that operate on the service, to set different values to the data that is stored in the service. The third button actually pulls the data from the service and applies to the controllers' data. This is just to simulate situations you might encounter where you are traversing back and forth in your routes and your controller gets re-instantiated when a user visits that part of the site again.

Community
  • 1
  • 1
tpie
  • 6,021
  • 3
  • 22
  • 41