AngularUI-Bootstrap Typeahead: Grouping results

I used to have a similar requirement and here is how I did it that time.

Example Plunker: http://plnkr.co/edit/zujdouvB4bz7tFX8HaNu?p=preview

The trick is to set the typeahead-template-url to a custom item template:

<input type="text" class="form-control" placeholder="Users loaded from local database"
    ng-model="selectedUser"
    typeahead="user as user.name for user in getUsers($viewValue)"
    typeahead-template-url="typeahead-item.html" />

The item template, this represent each item in a dropdown:

<div class="typeahead-group-header" ng-if="match.model.firstInGroup">Desc {{match.model.group}}</div>
<a>
  <span ng-bind-html="match.label | typeaheadHighlight:query"></span>
</a>

As you can see, there is an ng-if to show a group header if that item has a property firstInGroup set to true.

The firstInGroup properties are populated like this using lodashjs:

$scope.getUsers = function (search) {
  var filtered = filterFilter(users, search);

  var results = _(filtered)
    .groupBy('group')
    .map(function (g) {
      g[0].firstInGroup = true; // the first item in each group
      return g;
    })
    .flatten()
    .value();

  return results;
}

Hope this fit to your requirement too.

Leave a Comment