Angular Typeahead:点击建议并立即发表一篇文章

Angular Typeahead: click on suggestion and instantly make a post?

本文关键字:文章 一篇 Typeahead Angular      更新时间:2023-09-26

我正在做一个项目,我正在使用Siyfion的angular Typeahead。我有一个Typeahead用于搜索用户。当在建议下拉菜单中找到用户名时,您应该能够点击名称或按回车键直接发布帖子,而不是需要按下按钮来发布帖子。要做到这一点,我需要"捕捉"其中一个用户名上的click- or - return-事件。

下面你会发现它的html和js,我也做了一个柱塞,使事情更清楚。

有谁知道我怎么才能抓住点击和返回事件吗?欢迎所有的建议!

<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>
下面是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);
    };
});

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

下面是一个例子:

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

上面的"typeahead:select"代码将一个函数绑定到事件。当一个建议被点击时,或者当返回键被点击并且一个建议被突出显示时,这个将被触发。

从这里你可以在你的函数中做任何你想做的事情,所以在你的例子中,你想提交搜索。老实说,我对Angular不太熟悉,所以我不确定提交搜索的正确语法是什么。然而,你可以使用jQuery中的.trigger()方法来触发对搜索按钮的点击;虽然我知道这有点粗糙,但我相信有一种更优雅的方式来提交搜索

Siyfion的插件似乎没有足够的关于事件处理的文档。试试这个插件[https://github.com/borntorun/angular-typeaheadjs]

他们有非常好的关于事件处理的文档,这是专门针对AngularJS的。他们文档中的例子:

<angular-typeaheadjs angty-onselect="vm.onselect" ...>
  <input class="typeahead" type="text" ... />
</angular-typeaheadjs>
//on the controller
vm.onselect = function() {
  //do something 
}

或者你可以简单地说:

$scope.$on('typeahead:select', function() {
  //Your post code goes here....
});

希望这对你有帮助!