Bootstrap-UI Typeahead display more than one property in results list?

為{幸葍}努か 提交于 2019-11-27 10:41:57
pkozlowski.opensource

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!