Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on a project and I'm using the Siyfion's angular Typeahead. I have a Typeahead for searching users. When a username is found in the suggestions dropdown you should be able to click on a name or press enter to directly make a post instead of needing to press a button to do the post. For this to work I need to "catch" the click- or return-event on one of the user names.

Below you will find the html and the js for it and I also made a plunker to makes things more clear.

Does anybody know how I can catch the click and the return events? All tips are welcome!

<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>

Here is the JS code:

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);
    };
});
like image 720
H_C Avatar asked Aug 05 '15 09:08

H_C


1 Answers

Typeahead supports custom events which you can bind to a function to automatically submit your form. You can view all of the custom events available in the docs here.

Here's an example:

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

The above code "typeahead:select" binds a function to the event. This will fire when a suggestion is clicked on, or when the return key is hit and a suggestion is hightlighted.

From here you can do anything you want inside your function, so in your case you'd want to submit the search. Honestly I'm not that familiar with Angular so I'm not sure what the correct syntax would be to actually submit the search. You could however use the .trigger() method in jQuery to trigger a click on your search button; although I appreciate this is a bit hacky and I'm sure there is a more elegant way to submit the search.

like image 132
James Avatar answered Nov 12 '22 14:11

James