List auto-dividers in Ionic

This question came up on StackOverflow recently and I took a stab at answering it. The user had a list of data that included dates. They were looking to see if there was an easy way to add dividers to the list automatically. jQuery Mobile actually supports this out of the box - and supports it well. By default it will use the first letter of your list data as a separator (so "Andy" and "Al" will be prefixed with an "A" divider) but you can also use a function to specify your own logic.

While there is no similar feature in Ionic (I filed this issue for it) it isn't too difficult to build it manually. The CodePen I built handles it like so.

First, the controller code modifies the array to include an item for each necessary divider.

.controller('RootCtrl', function($scope) {

  //orig data
  var list = [];
  list.push({name:"Gary"});
  list.push({name:"Gosh"});
  list.push({name:"Ray"});
  list.push({name:"Sam"});
  list.push({name:"Sandy"});

  $scope.list = [];
  var lastChar = '';
  for(var i=0,len=list.length; i<len; i++) {
    var item = list[i];

    if(item.name.charAt(0) != lastChar) {
      $scope.list.push({name:item.name.charAt(0),letter:true});
      lastChar = item.name.charAt(0);
    }
    $scope.list.push(item);
    
  }
})

That feels lame - I mean modifying the list - but I'm doing it in my controller and not the back end service so I can still sleep at night. The next change is to the front end. (And the Ionic team deserves credit for this as I modified this from one of their examples.)

<ion-list type="list-inset">
      <ion-item ng-repeat="person in list" ng-class="person.letter? 'item-divider':''">
        {{person.name}}
      </ion-item>
    </ion-list>

Basically - since a list divider is simply a class change, we can iterate over our array and include the class when the letter property exists in the data. I don't like the fact that I use person.name when I'm doing a letter, but, it works. I really think smarter people than me can do this nicer, so please feel free to fork the CodePen and make it nicer!

Code Pen: List Test - Autodividers

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate looking for his next gig. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments