Typeahead.js建议不正确渲染

时间:2015-01-12 15:16:57

标签: javascript typeahead.js

我正在使用Typeahead.js插件。我正在尝试为建议创建自定义模板。目前,我有以下内容:

var suggestions = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: '/api/suggests?querytext=%QUERY'
});
suggestions.initialize();

$(document).ready(function() {
  $('input.typeahead').typeahead(
    { minLength: 3 },
    {
      name: 'suggestions',
      source: suggestions.ttAdapter(),
      templates: {
        suggestion: function(data) {
          var str = '';
          str += '<div>Result: ';
          // if suggestion is a Customer show 1 icon and the Name
          // elseif suggestion is a Product show a different icon and the name          
          str += '</div>';
          return str;
        }
      }
    }
  );
});

建议突然出现。但是,我无法从结果中获取属性值。当Bloodhound请求建议时,我得到一个如下所示的结果集:

{
  "Results":[
    {
      "Type":"Customer",
      "Id":5,
      "Name":"Bill",
      "LastUpdated":"01-01-2015"
    },
    {
      "Type":"Customer",
      "Id":135,
      "Name":"Billows",
      "LastUpdated":"01-02-2015",
    },
    {
      "Type":"Product",
      "Id":241,
      "Name":"Bill Check",
      "LastUpdate":"01-04-2015"
    }
  ],
  "TotalResults":3,
  "TotalCustomers":2,
  "TotalProducts":1
}

如何为模板中的单个建议获取单独的NameType值,以便我可以正确呈现它?

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个

var suggestions = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/api/suggests?querytext=%QUERY',
        filter: function(list) {
            var suggestions = list.Results;
            return $.map(suggestions, function(suggestion) { return { Type: suggestion.Type, Id: suggestion.Id, Name: suggestion.Name, LastUpdated: suggestion.LastUpdated }; });
        }
    }
});
suggestions.initialize();

$(document).ready(function () {
    $('input.typeahead').typeahead(
            { minLength: 3 },
            {
                name: 'suggestions',
                source: suggestions.ttAdapter(),
                templates: {
                    suggestion: function (data) {
                        var str = '';
                        str += '<div>Result: ';
                        // get value by data.Type data.Name
                        str += '</div>';
                        return str;
                    }
                }
            }
    );
});