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.
please see here http://plnkr.co/edit/DmoEWzAUHGEXuHILLPBp?p=preview
instead of creating new objects here:
angular.forEach(res.data, function(item) { users.push(item.UserName + " - " + item.UserDepartment); });
use create template :
<script type="text/ng-template" id="customTemplate.html"> <a> {{ match.model.name}} - department : {{match.model.dept}}</a> </script>
and use it in your Typeahead directive
<input type="text" ng-model="selected" typeahead="user.name as user for user in users | filter:$viewValue | limitTo:8" class="form-control"typeahead-template-url="customTemplate.html">