I'm using ui-bootstrap typeahead. It works brilliantly! However, I'm wondering if its possible to display multiple properties or even HTML in the results list. Typical problem: the search returns more than one object with the same value. Eg search for 'amazing grace' return ['amazing grace', 'amazing grace'] where one is the movie and one is the song. I would like the results list to be more like:
amazing grace | movie
amazing grace | song
... so the user knows exactly what they're selecting. Even better would be an icon next to the title. In other words, each result in the list contains some HTML. Can either of these be done out of the box?
The thing to ntice about the typeahead
directive from http://angular-ui.github.io/bootstrap/ is that tries to mimic syntax used by the select directive from AngularJS. It means that all the expressions used to select a model to bind and a label are AngularJS expressions. This in turns means that you can use whatever AngularJS expression to calculate the text of your label.
For example, to display your desired text you could write:
typeahead="item as item.title + ' (' + item.type + ')' for item in titles | filter:{title:$viewValue}"
Provided that your data model looks like follows:
$scope.titles = [
{title: 'Amazing Grace', type: 'movie'},
{title: 'Amazing Grace', type: 'song'}
];
Working plunk here: http://plnkr.co/edit/VemNkVnVtnaRYaRVk5rX?p=preview
Writing complex expressions for a label in the typeahead
attribute might get ugly but nothing stops you from moving label calculation logic to a function exposed on a scope, ex.:
typeahead="item as label(item) for item in titles | filter:{title:$viewValue}"
where the label
is a function exposed on a scope:
$scope.label = function(item) {
return item.title + ' (' + item.type + ')';
};
Another plunk: http://plnkr.co/edit/ftKZ96UrVfyIg6Enp7Cy?p=preview
As far as your question regarding icons go - you could embed HTML in the label expressions but this gets awful to write and maintain. Fortunately the typeahead directive allows you to provide a custom template for your matched item, like so:
typeahead-template-url="itemTpl.html"
In the custom template you can use any expressions or AngularJS directive you would like. Adding icons becomes trivial with a little help from the ngClass
directive:
<script type="text/ng-template" id="itemTpl.html">
<a tabindex="-1">
<i ng-class="'icon-'+match.model.type"></i>
<span ng-bind-html-unsafe="match.model.title | typeaheadHighlight:query"></span>
</a>
</script>
And the working plunk: http://plnkr.co/edit/me20JzvukYbK0WGy6fn4?p=preview
Pretty neat little directive, isn't it?