1

我正在使用 sifyion 的 angularJS 库进行 typeahead,它实际上使用 typeahead.js 和 Bloodhound.js 和 jquery。我有 typeahead.js v 0.10.2 和 jquery 1.10.2。我的目标是创建一个搜索功能,用户只能从建议中进行选择。所以我以一种方式实现它,如果没有选择建议的结果,则提交带有 Null 参数的查询,否则提交建议。我已将我的选项设置为

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 存储库中查找了解决问题的解决方案。我一直无法找到让它们为我工作的方法。请帮助我或建议我以不同的方式实现它。

提前致谢

4

1 回答 1

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;
    }
  });
}());
于 2014-05-23T18:32:39.617 回答