2014-04-22 70 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; 
    } 
    }); 
}());