注意关于来自
http://angular-ui.github.io/bootstrap/ 的
typeahead
指令的一件事是,它试图模仿AngularJS的
select 指令 使用的语法。这意味着用于选择要绑定的模型和标签的所有表达式都是
AngularJS 表达式 。这又意味着您可以使用任何 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>
这是工作的plunk: http://plnkr.co/edit/me20JzvukYbK0WGy6fn4?p=preview
相当不错的指令,不是吗?