Angular Typeahead:点击建议并立即发帖?

H_C*_*H_C 6 javascript angularjs typeahead.js

我正在研究一个项目,我正在使用Siyfion的角度Typeahead.我有一个Typeahead用于搜索用户.如果在建议下拉列表中找到用户名,您应该可以点击名称或按Enter键直接发帖,而不需要按下按钮进行发布.为此,我需要在其中一个用户名上"捕获"click-or-return事件.

下面你会发现HTML和它的JS,我也做了一个plunker以使事情变得更加清晰.

有谁知道我怎么能抓住点击和返回事件?欢迎所有提示!

<body ng-controller="MainCtrl">
    <input class='typeahead' type="text" sf-typeahead options="exampleOptions" datasets="numbersDataset" ng-model="selectedName">
    <input type="button" value="Post user to server" type="text" ng-click="postUserToServer(selectedName.id)">
</body>
Run Code Online (Sandbox Code Playgroud)

这是JS代码:

var app = angular.module('plunker', ['siyfion.sfTypeahead']);

app.controller('MainCtrl', function($scope) {

    $scope.selectedNumber = null;

    // instantiate the bloodhound suggestion engine
    var numbers = new Bloodhound({
        datumTokenizer: function(d) { 
        return Bloodhound.tokenizers.whitespace(d.name); },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: [
                   { name: 'John',id: 1 },
                   { name: 'Richard', id: 2 },
                   { name: 'Dennis', id: 3 }
        ]
    });

    // initialize the bloodhound suggestion engine
    numbers.initialize();

    $scope.numbersDataset = {
        displayKey: 'name',
        source: numbers.ttAdapter()
    };

    // Typeahead options object
    $scope.exampleOptions = {
        highlight: true
    };

    $scope.postUserToServer = function(userId){
        alert(userId);
    };
});
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 1

Typeahead 支持自定义事件,您可以将其绑定到函数以自动提交表单。您可以在此处查看文档中提供的所有自定义事件

这是一个例子:

$('.typeahead').bind('typeahead:select', function(ev, suggestion) {
  console.log('Selection: ' + suggestion);
});
Run Code Online (Sandbox Code Playgroud)

上面的代码“typeahead:select”将函数绑定到事件。当单击建议或按下返回键并突出显示建议时,将触发此操作。

从这里,您可以在函数内执行任何您想要的操作,因此在您的情况下,您需要提交搜索。老实说,我对 Angular 不太熟悉,所以我不确定实际提交搜索的正确语法是什么。不过,您可以使用jQuery 中的.trigger()方法来触发搜索按钮的点击;尽管我知道这有点老套,但我确信有一种更优雅的方式来提交搜索。