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

后端 未结 1 1354
自闭症患者
自闭症患者 2020-12-02 07:47

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

相关标签:
1条回答
  • 2020-12-02 08:29

    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?

    0 讨论(0)
提交回复
热议问题