Typeahead.js 0.10.x : how to show number of results per category

标签 typeahead.js twitter-typeahead

Typeahead.js 0.10 支持页眉和页脚以及搜索结果的模板。我希望能够获得每个类别的实际结果/建议数量(即忽略限制值)并将其显示在类别名称标题中。

例如 -

结果:

  • A类 (24 个结果)
  • -A1
  • -A2
  • -A3
  • B类 (167 个结果)
  • -B1
  • -B2
  • -B3

  • 我的模板目前看起来像这样:
    {
    name: 'Applications',
    displayKey: 'value',
    source: app.ttAdapter(),
    extraVars:Handlebars.registerHelper("numResults",function(){
        return (  "HowToGetTheseResults??" );
    }),
    templates: {
        header:Handlebars.compile([
            '<h3 class="applications"> Applications ({{numResults}}) results  </h3>'
        ].join('')),
    
        suggestion: Handlebars.compile([
            '<p><b>{{value}}</b> </p>'
        ].join(''))
    }
    

    有没有一种简单的方法可以预先输入以返回结果/建议的数量?我确定 typeahead 对象(或猎犬对象?)必须将这些数据存储在某个地方。

    最佳答案

    您可以定义自己的函数来处理用户输入的查询。

    我做了一个样本 fiddle :http://jsfiddle.net/dtengeri/6ApJg/

    基本思想是您手动从 Bloodhound 引擎获取建议,并且只将所需数量的结果传递给 typeahead。

    // Custom source function in the dataset definition.
    source: function (query, cb) { 
      // Get the data from the Blodhound engine and process it.
      nbaTeams.get(query, function (suggestions) {
        // Show only the first 3 results.
        cb(suggestions.slice(0, 3));
        // Set the headers content.
        $('#nba-header').text(suggestions.length);
      })
    },
    

    您必须在标题模板中定义一个 HTML 元素,您将在其中放置结果数量。 (本例中带有 id #nba-header 的跨度。)
    templates: {
      // Insert an HTML element where you will place the number of results.
      header: '<h3 class="league-name">NBA Teams (<span id="nba-header"></span>)</h3>'
    }
    

    为了获得所有结果,您应该在 Bloodhound 引擎中设置一个较高的数字作为限制:
    var nbaTeams = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      local: nba(),
      limit: Number.MAX_VALUE // Set the limit as high as possible.
    });
    

    关于Typeahead.js 0.10.x : how to show number of results per category,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361286/

    相关文章:

    elasticsearch - Typeahead/Rails : Not working

    html - 如何使用 twitter 的 typeahead 实际提交数据

    jquery - Algolia 自动完成 - 如何做出响应

    jquery - Twitter Typeahead - 重复的 AJAX 建议

    javascript - 使用 Post ajax 调用进行预输入搜索不起作用

    javascript - 更改 Twitter Typeahead 返回的内容

    ruby-on-rails-4 - Algolia - 搜索条件以查看字符串数组

    javascript - 预输入搜索建议 undefined - Remote Ajax

    javascript - 为什么我的 ng-model 在 Firefox 中不使用 Typeahead 更新?

    javascript - 当我从下拉列表中选择一个选项时,jQuery typeahead 停止工作