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
非常简洁的小指令,不是吗?