【发布时间】:2017-02-15 22:36:07
【问题描述】:
我在 Laravel 5.3 中使用 twitter typeahead。请注意,这是我的产品数据及其制造商品牌 (FK):
[
{
"id": 2,
"name": "iphone",
"created_at": "2017-02-08 06:12:34",
"updated_at": "2017-02-08 06:12:34",
"user_id": 1,
"brand_id": 1,
"msds_url": "google.com",
"gravity": 1.03,
"recipe_id": null,
"relevance": 210,
"brand": {
"id": 1,
"name": "apple",
"created_at": "2017-02-08 03:00:49",
"updated_at": "2017-02-08 03:00:49",
"user_id": 1,
"abbreviation": "AP",
"visible": 1
}
}
]
当远程源 JSON 数组映射到名为 value 的 js 对象数组时,建议下拉列表中的数据将按照其写入方式进行格式化,例如'Apple - iPhone'。
var engine = new Bloodhound({
datumTokenizer: function(datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
wildcard: '%QUERY',
url: '/find?q=%QUERY%',
transform: function(response) {
console.log(response);
// Map the remote source JSON array to a JavaScript object array
return $.map(response, function(product) {
return {
value: product.brand.name+' - '+product.name,
other: product
};
});
}
}
});
// Instantiate the Typeahead UI
$('#search').typeahead( null,{
display: 'value',//choose a key from the map
highlight: true,
hint: true,
source: engine
});
我还想做的是将brand.id(将为 1)和product.id(将为 2)转换为同一输入上的某些数据属性,因此我捕获了该事件并记录了“选定的建议” ' 用户拍摄的。
$("#search").on("typeahead:select", function(ev, suggestion) {
console.log(suggestion);
});
问题在于它无法让我访问完整的数据数组,因为它是在寻血猎犬部分的 map 函数中专门格式化的
// Map the remote source JSON array to a JavaScript object array
return $.map(response, function(product) {
return {
value: product.brand.name+' - '+product.name, //this format
other: product //full access to object
};
});
所以我将display 切换为other 而不是value,以便传递完整的对象而不是品牌名称和产品名称。
$('#search').typeahead( null,{
//display: 'value',
display: 'other',
highlight: true,
hint: true,
source: engine
});
现在,当下拉列表中出现建议时,它会显示[object object],因为与以前不同,我还没有访问过它。
如何访问对象并正确格式化它并保持对品牌 ID 和产品 ID 的访问?这样以后当我提交表单时,我可以将选定的产品 id 与我的产品表项进行匹配。
【问题讨论】:
标签: javascript laravel typeahead.js bloodhound