所以我有一个传递的对象,如下所示:
[{id: 1, name: 'Project A', type: 'C'}, {id: 2, name: 'Project B', type: 'A'},]
而我正试图通过Bloodhound引擎传递它:
var mySource = new Bloodhound({
identify: function (obj) { return obj.id; },
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
local: datasource
});
由typeahead.js使用如下:
$(control)
.typeahead({
hint: true,
highlight: true,
minLength: 0
},
{
source: mySource
});
但它根本不可行。我不确定我做错了什么。
我只想要名字可以搜索。 ID和类型将在稍后传递给.on('typeahead:autocomplete')
。
编辑:控制台中没有错误,并在创建猎犬对象后生成一个猎犬对象时放置console.log(mySource);
:
首先在你的js中设置Bloodhound:
var dataSetBloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: data
});
其中data
是数组中的建议列表。
我的例子是
data = [ { name: "Foo", url: "/bar.jpg" }, etc, etc ]
这就是我在Bloodhound.tokenizers.obj.whitespace('name')
中使用name的原因,因为我希望我的建议是数据数组中的name
。
在我的HTML中我有我的输入:
<input id="quick-search-input" type="text" class="form-control" placeholder="Products" data-provide="typeahead"/>
//The important thing here is 'data-provide="typeahead"'
哪个是建议框将作用的输入。
然后在它后面设置js:
$('#quick-search-input').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name : 'NameForFormInput',
displayKey: 'name',
templates:
{
suggestion: function(data)
{
return '<li class="list-group-item">
<p class="predictionText">'+data.name+'</p></li>';
}
},
source : dataSetBloodhound
});
我认为这是你出错的地方,因为我在设置时遇到了类似的问题,但是当我实现模板时修复了它。 css也会根据你的使用情况而有所不同。