以编程方式触发typeahead.js结果显示

38
我正在使用 Twitter 的 typeahead.js(https://github.com/twitter/typeahead.js/)在一个输入字段上,该字段已经通过查询字符串预填充。加载页面后,我想以编程方式触发 typeahead 结果的显示,而不需要用户在表单字段中输入任何内容。
默认情况下,只有当用户手动在输入字段中键入内容时,typeahead.js 才会被触发,而我无法找到 typeahead.js 中可调用以触发结果显示的任何方法。
非常感谢指点。
谢谢!

1
非常感谢大家提供的所有出色答案!我选择了通过触发输入来实现的那个,因为这也强制 typeahead 在显示结果之前搜索关键字(这是我的要求,我意识到这并没有在我的问题中提到)。再次感谢。Stackoverflow 比切片面包好得多。 - zıəs uɐɟəʇs
可以使用“预取”功能。 - Saahithyan Vigneswaran
17个回答

2
我查看了源代码并发现了这种未记录的方法:
var $myinput = $('#myinput');
$myinput.data('typeahead')._showDropdown()

2
这应该可以与“旧版”Bootstrap typeahead插件配合使用:
$(".typeahead").eq(0).trigger("keyup");

很遗憾没有在IE上进行测试... 不知道新的typeahead插件是什么...

1
其他答案都有帮助,但未解决我的问题。这种解决方案不涉及自定义任何 angular-ui 代码本身,并且只触发 typeahead 在显式按钮单击时获取结果的目的。
为此,我必须在另一个(禁用的)文本字段上覆盖一个文本字段,该文本字段是具有 typeahead 的实际文本字段。没人会知道另一个存在,但它需要存在于 angular-ui 中以在正确位置启动菜单。您不能将其设置为隐藏字段,因为它将无法在正确位置显示菜单。
以下指令将监视 typeaheadTexttypeaheadTrigger 变量,以便在按钮触发时(通过将触发器设置为 true)填充 disbled 字段。该指令具有隔离作用域,因此它不依赖于传递的任何其他内容。
directive('typeaheadTrigger', function() {
  return {
    require: ["ngModel"],
    scope: {
      typeaheadText: '=',
      triggerFlag: '='
    },
    link: function(scope, element, attr, ctrls) {
      scope.$watch('triggerFlag', function(value) {
        if (scope.triggerFlag) {
          ctrls[0].$setViewValue(scope.typeaheadText);
          scope.typeaheadText = '';
          scope.triggerFlag = false;
        }
      });
    }
  };
})

控制器为此设置了一些内容 - 触发器和文本作用域变量在对象内。这演示了如何做到这一点 - 理想情况下,您应该将整个内容包装在另一个指令中,以便在隐藏细节的同时可以在应用程序中使用它。
这是plunk链接:http://plnkr.co/edit/UYjz6F5ydkMQznkZAlfx?p=preview

1

注意这个!

对于那些想手动触发类型自动完成行为(例如在按钮点击上)的人,我强烈建议不要这样做。

我曾为此解决方案而努力了一整天,几乎失去了全部时间(在我的情况下是一个按钮点击事件)。

对于那些真的想走这条“黑暗之路”的人,我会与你们分享我的丑陋代码,让它正常工作:

//Removes default features of typeahead
//This means that typeahead will not work like an "autocomplete", it only will be trigged when the user Click in #btnSearch button!
var txt = $("#typeahead");
//Save input events in variables (we'll need them)
eventInput = $._data(txt[0], "events").input[0];
eventBlur = $._data(txt[0], "events").blur[1];
//Remove input events
txt.unbind("blur");
txt.unbind("input");

//Set click event that triggers typeahead features manually
$("#btnSearch").click(function () {
    //Clears the cache of engine for it call ajax again, without it when the term was already searched the ajax is not called!
    engine.clearRemoteCache();

    txt.focus(); //When we click in a button, the focus from input is lost, so we set it again to not lose the behaviors of keyboard keys (up, down, tab, etc)
    txt.bind("input", eventInput); //Bind the event that we had saved
    txt.trigger("input"); //Trigger input (like the answer from @epascarello)
    txt.unbind("input"); //Removes it again 
});

//Set event on parent of the suggestion's div, this makes the sugestion div close when user click outside it
$("body").click(function () {            
    if (eventBlur != undefined) {
        if ($(".tt-dropdown-menu:visible").length > 0) {
            eventBlur.handler(); //This event closes the suggestion menu
        }
    }
});

我所做的另一件事是更改typeahead.js事件"_checkInputValue"的代码。我更改了以下内容:

areEquivalent = areQueriesEquivalent(inputValue, this.query);

转换为:

areEquivalent = false;//areQueriesEquivalent(inputValue, this.query);

我将其设置为false,因为typeahead不会向服务器发送两个相同的请求。这种情况发生在用户点击搜索按钮两次时(也就是说,当他搜索已经搜索过的相同文本时)。无论如何,如果您使用的是本地数据,则不需要这样做。

1
这对我有用。
$( document ).ready(function() {
    $('#the-basics .typeahead').typeahead({
      hint: false,
      highlight: true,
      minLength: 0
    },
    {
      name: 'states',
      displayKey: 'value',
      source: substringMatcher(states)
    });

    //set a value to input to trigger opening
    $(".typeahead").eq(0).val("a").trigger("input");
    //remove value for end user
    $(".typeahead").eq(0).val("");

});

看这里的例子:http://joshuamaynard.com/sandbox/autocomplete


这个可以工作,但不是完美的,当你选择后再次点击时不会显示。 - Eben Watts

0

我使用这个手动触发选择,当tt-dataset中只有1个项目时。添加这个功能是很有意义的。

$("#mytypeahead").keyup(function (e) {
                var charCode = (typeof e.which === "number") ? e.which : e.keyCode;
                if (charCode == 13) {
                    if ($(this).parent().find(".tt-dataset").children().length == 1) {
                        //This is how we are submitting a single selection on enter key
                        $(this).parent().find(".tt-dataset").children(0).addClass("tt-cursor");
                        var kde = jQuery.Event("keydown");
                        kde.which = 13;
                        $(this).trigger(kde);                           
                    }    
                }                    
            });

0

我尝试了这里的每种方法,但都没有起作用,只有使用

$(".typeahead").val('hi').trigger('keyup');
$(".typeahead").val('hi').trigger('keydown');

上述代码对我有效。不知道具体发生了什么,但仅使用其中一个不起作用,只有同时使用两个才能起作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接