Typeahead templating, if/else

孤街醉人 提交于 2020-01-03 05:45:08

问题


thanks for the help on this question: Typeahead result formatting, this is a follow up.

My JSON looks like

[{ name="Long Island", type="2", id="1234"}, { name="New York", type="1", id="5678"}]

In the drop down list I need to be able to seperate type 1 from type 2, so

Type 1 heading

type 1 item

type 1 item*

Type 2 heading

type 2 item

type 2 item

If there are no results for type 1, then don't show the heading. Same for type 2.

Is this possible with typeahead and a templating engine? I'm using Hogan but I'm not fussy.


回答1:


The "Typeahead" way of doing this is to separate your dataset into 2 datasets, one that will only return "type 1" items and another that will return only "type 2" items. In typeahead, each dataset can have its own header, which will behave exactly the way you want it.

$autocomplete.typeahead([{
    name: 'location 1',
    remote: {
        url: 'http://pathtomysite.com/%QUERY?type=1',
        dataType: 'jsonp',
        valueKey: 'name'
        filter: function (parsedResponse) { return parsedResponse.locations; }
    },
    template: [
        '<p class="repo-name">{{name}}</p>',
        '<p class="repo-description">{{id}}</p>'
    ].join(''),
    header: '<b>Type 1</b>'
    engine: Hogan
}, {
    name: 'location 2',
    remote: {
        url: 'http://pathtomysite.com/%QUERY??type=2',
        dataType: 'jsonp',
        valueKey: 'name'
        filter: function (parsedResponse) { return parsedResponse.locations; }
    },
    template: [
        '<p class="repo-name">{{name}}</p>',
        '<p class="repo-description">{{id}}</p>'
    ].join(''),
    header: '<b>Type 2</b>'
    engine: Hogan
}])



回答2:


Given that you don't have control over the JSON part, you have 2 options:

Option 1

Use 2 datasets, with the same query. In one of them, the filter will only return "type 1" entries, in the other the filter will only return "type 2" answers.

That's twice the calls to the JSON, so twice the load on your server. The client side will not see a delay, though, as the queries are concurrent.

That's a hackish solution, but OTOH it's clean (client-side-wise), and requires very little code.

Option 2

Use only 1 dataset, and so some work in your filter. Basically, return an array with an entry for the "type 1" header, then all the type 1 entries, then an entry for the "type 2" header, then all the type 2 entries.

The array is an array of objects. Each object will also have a class member. In the entries for the "type 1" and "type 2" headers set the class to "header" or something along the lines, and:

1) Have your template include the class. 2) Have your CSS make the class unselectable, unclickable, and styled the way you want it.

I like option #1 better.



来源:https://stackoverflow.com/questions/19722627/typeahead-templating-if-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!