2014-04-22 53 views
1

我使用sideion for angularJS库作为typeahead,它实际上使用typeahead.js和bloodhound.js和jquery。我有typeahead.js v 0.10.2和jquery 1.10.2。 我的目标是创建一个搜索功能,用户只能从建议中进行选择。所以我已经以一种方式实现它,如果没有选择含有建议的结果,则带有空参数的查询被提交,否则提交建议被提交。我已经把我的选项typeahead.js默认选择第一个建议

minLength: 1, 
hightlight: true, 
editable: false 

我有三个数据集,如:

var bloodhoundStores = new Bloodhound({ 
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    prefetch: { 
     url:'/url/param', 
     filter: function(stores){ 
      return $.map(stores,function(store){return {name: store.name}}) 
     } 
    } 
}); 

我呼吁所有的人都清楚缓存,之后对其进行初始化,只是为了让你知道。我不是在这个非常专业,但这样做解决了我的目的

bloodhoundStores.clearPrefetchCache(); (on all three datasets) 
. 
bloodhoundStores.initialize(); (on all three datasets) 

然后我将它设置为建议呈现,如:

{ 
    name: 'Locality', 
    displayKey: 'name', 
    source: bloodhoundLocality.ttAdapter(), 
    templates:{ 
     header: '<h4 style="padding-bottom: 2px;"><i class="fa fa-location-arrow"></i>Locality</h4>', 
     empty:['<p>','<span>No results found</span>','</p>'].join('\n'), 
     suggestion: Handlebars.compile('<p><span class="sentence-case">{{name}}</span></p>') 
    } 
} 

我的问题是,如果在检索词的用户类型,我想要选择第一个建议,如果有的话。我在twitter的typeahead.js github存储库中查找了解决方案的解决方案。我一直无法找到让他们为我工作的方法。请帮助我,或者建议我采用不同的方式来实施它。

在此先感谢

+0

我也有一个问题,通常右箭头自动完成搜索查询,但如果用户按下按键,设有带光标在最后的一个建议。向右箭头键现在不会自动完成查询,用户必须再次按Tab。建议我一些解决方法 –

回答

1

这里是我的解决方案:

我有一个封装了所有我的搜索形式逻辑的,包括预输入源(以及相关的)封闭。它看起来有点像这样:

(function() { 
    var $searchBox, 
     doSearch, 
     firstMatch, 
     searchResultHandler, 
     typeaheadCallback, 
     typeaheadSource; 

    typeaheadSource = function(query, cb) { 
    typeaheadCallback = cb; 
    doSearch(query); 
    }; 

    doSearch = function(term) { 
    // Do some stuff here to query. 
    // When the results come back, fire off a call to searchResultHandler. 
    }; 

    searchResultHandler = function(response) { 
    var data = JSON.parse(response.body); // I'm using sock.js in my app 

    firstMatch = data[0].termToFillInSearchBox; 

    if (typeaheadCallback) { 
     typeaheadCallback(data); 
    } 
    }; 

    $searchBox.on("typeahead:closed", function(evt) { 
    // Match what is in the search field against some expected pattern. 
    // In my case, I'm looking for "Some Value.1234". 
    // If the input doesn't match, and I have something in "firstMatch" then 
    // substitute the value. 
    if (! /\w+\.\d+/.test($searchBox.val()) && firstMatch !== undefined) { 
     $searchBox.val(firstMatch); 
     firstMatch = undefined; 
    } 
    }); 
}());