【问题标题】:Bootstrap-UI Typeahead display more than one property in results list?Bootstrap-UI Typeahead 在结果列表中显示多个属性?
【发布时间】:2014-07-15 18:30:41
【问题描述】:

我正在使用 ui-bootstrap 预输入。它工作得很好!但是,我想知道是否可以在结果列表中显示多个属性甚至 HTML。典型问题:搜索返回多个具有相同值的对象。例如,搜索 'amazing grace' 返回 ['amazing grace', 'amazing grace'] 其中一个是电影,一个是歌曲。我希望结果列表更像:

amazing grace | movie
amazing grace | song

...所以用户确切地知道他们在选择什么。更好的是标题旁边的图标。换句话说,列表中的每个结果都包含一些 HTML。可以开箱即用吗?

【问题讨论】:

标签: angularjs bootstrap-typeahead angularjs-bootstrap


【解决方案1】:

http://angular-ui.github.io/bootstrap/ 中的 typeahead 指令要注意的是它试图模仿 AngularJS 中的 select directive 使用的语法。这意味着用于选择要绑定的模型和标签的所有表达式都是AngularJS expressions。这反过来意味着您可以使用任何 AngularJS 表达式来计算标签的文本。

例如,要显示您想要的文本,您可以编写:

typeahead="item as item.title + ' (' + item.type + ')' for item in titles | filter:{title:$viewValue}"

假设您的数据模型如下所示:

$scope.titles = [
    {title: 'Amazing Grace', type: 'movie'},
    {title: 'Amazing Grace', type: 'song'}
  ];

在这里工作: http://plnkr.co/edit/VemNkVnVtnaRYaRVk5rX?p=preview

typeahead 属性中的标签编写复杂的表达式可能会很难看,但没有什么能阻止您将标签计算逻辑移动到作用域上公开的函数中,例如:

typeahead="item as label(item) for item in titles | filter:{title:$viewValue}"

label 是在作用域上公开的函数:

$scope.label = function(item) {
    return item.title + ' (' + item.type + ')';
  };

另一个笨蛋:http://plnkr.co/edit/ftKZ96UrVfyIg6Enp7Cy?p=preview

就您关于图标的问题而言 - 您可以在标签表达式中嵌入 HTML,但这会导致编写和维护起来很糟糕。幸运的是,typeahead 指令允许您为匹配的项目提供自定义模板,如下所示:

typeahead-template-url="itemTpl.html"

在自定义模板中,您可以使用任何您想要的表达式或 AngularJS 指令。在ngClass 指令的帮助下添加图标变得微不足道:

<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>

还有工作的笨蛋:http://plnkr.co/edit/me20JzvukYbK0WGy6fn4?p=preview

非常简洁的小指令,不是吗?

【讨论】:

  • 非常整洁!不是你写的吗?? ;) 出于某种原因,我很难找到好的文档。如果此页面有一个包含所有选项等的文档链接,那就太好了angular-ui.github.io/bootstrap/#/typeahead
  • 如何从模板中嵌入的链接调用控制器函数?该函数从未被调用,所以看起来我们在不同的范围内?详细解释见:stackoverflow.com/questions/18441928/…
  • 非常感谢您提供样品和 Plunkr。我已经在 ng-grid 中与 typeahead 斗争了 2 天了,你的例子帮助我理解了一些事情。
  • 如果您有任何问题(例如弹出窗口为空),请尝试使用bind-html-unsafe 而不是ng-bind-html-unsafe。 (这对我有用 - 我正在将 UI.bootstrap.typehead 用于 boostrap3(boostrap3 分支)
  • 模板很棒,但是如何让它访问范围参数呢?详情请参阅http://stackoverflow.com/questions/24833151/how-to-make-bootstrap-typeahead-template-to-use-scope-parameter-in-angular 我的问题。
猜你喜欢
  • 2016-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多