jquery-typeahead没有显示建议

时间:2017-06-27 11:49:48

标签: jquery angularjs typeahead.js

我在我的角度应用中添加了jquery-typeahead

Html是:

<input class="js-typeahead-locations_v1" name="locations_v1[query]" type="search" placeholder="Search here" autocomplete="off">

控制器:

$.typeahead({
        input: '.js-typeahead-locations',
        minLength: 1,
        order: "asc",
        dynamic: true,
        delay: 500,
        backdrop: {
          "background-color": "#fff"
        },
        template: function (query, item) {
          var color = "#777";

          return '<span class="row">' +
            '<span class="username">{{name}} <small style="color: ' + color + ';">({{status}})</small></span>' +
            '<span class="id">({{id}})</span>' +
            "</span>"
        },
        emptyTemplate: "no result for {{query}}",
        source: {
          matches: {
            display: "name",
            data: [{
              "id": 415849,
              "name": "an inserted user that is not inside the database",
              "avatar": "https://avatars3.githubusercontent.com/u/415849",
              "status":  "contributor"
            }],
            ajax: function (query) {
              return {
                type: "GET",
                url: $rootScope.apiUrl+'search/query',
                path: "data.matches",
                data: {
                  name: "{{query}}"
                },
                callback: {
                  done: function (data) {
                    console.log(data);
                    return data;
                  }
                }
              }
            }
          },
        },
        callback: {
          onClick: function (node, a, item, event) {

            // You can do a simple window.location of the item.href
            alert(JSON.stringify(item));

          },
          onSendRequest: function (node, query) {
            console.log('request is sent')
          },
          onReceiveRequest: function (node, query) {
            console.log('request is received')
          }
        },
        debug: true
      });

我正在以json格式从服务器获得响应:

matches :[ 
 {name : 'loc_id_1',id : 'loc_id_0'},
 { name: 'loc_name_1',id:'loca_name_1'}
}

我在每次按键时都会收到回复,但我无法在浏览器上显示。

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

出于某种原因,Typeahead插件需要特定的HTML结构,如下所示:

<form>
<div class="typeahead__container">
    <div class="typeahead__field">

        <span class="typeahead__query">
            <input class="js-typeahead-locations_v1"
                   name="locations_v1[query]"
                   type="search"
                   autocomplete="off">
        </span>
        <span class="typeahead__button">
            <button type="submit">
                <span class="typeahead__search-icon"></span>
            </button>
        </span>

    </div>
</div>

我这样使用它而不是跟随html结构:

<input class="js-typeahead-locations_v1" name="locations_v1[query]" type="search" placeholder="Search here" autocomplete="off">