user3125823 user3125823 - 2 years ago 327
AngularJS Question

Elasticsearch autocomplete with AngularJS typeahead

Building an autocomplete feature using Elasticsearch and AngularJS UI bootstrap typeahead. Nearly finished but I'm having trouble getting the results to display in the dropdown.

What currently appears in the dropdown when I press the letter a and I know there are suggestions for that letter is:

[object Object]

This is my controller code

$scope.getSuggestions = function(query) {
$scope.isSearching = true;
return searchService.getSuggestions(query).then(function(es_return){
var phrases;
var phrases = es_return.hits.hits;
return $scope.autocomplete.suggestions = phrases;
$scope.isSearching = false;

And this is my html form

<form ng-submit="search()" class="form-horizontal col-md-8 col-md-offset-2" id="hp-search-form">

I'm using an ES
query coupled with a
analyzer which is working nicely - getting expected results in Sense. If I go to the Sense plugin for ES, I get many responses back when typing "a", so I know the ES part of this working. Where am I going wrong with UI bootstrap typeahead?

Answer Source

There are two issues with your approach, considering the following lines of code:

return $scope.autocomplete.suggestions = phrases;
$scope.isSearching = false;
  • The first line above will have the phrases as an array, so you will get [object Object] as the output. Replace it using phrases[0] or check your console for what's it returning.
  • The second line will never be executed as it returns the control to the caller before it executes. That's an orphaned instruction.

So change your code to:

$scope.isSearching = false;
return $scope.autocomplete.suggestions = phrases[0]; // Verify this with console.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download