Having some success with AngularJs autocomplete feature

Currently working on a small search application that utilizes Elasticsearch and AngularJS. I have made progress in implementing autocomplete functionality using the AngularJS Bootstrap typeahead feature. However, I am encountering difficulties in displaying the actual suggestions returned by Elasticsearch.

I have a function that retrieves results from Elasticsearch as a promise:

    this.getSuggestions = function(query) {
    var deferred = $q.defer();

    esClient.search({
      index: 'autocomplete',
      body: {
        "query": {
          "match_phrase_prefix": {
            "autocomplete_field": {
            "query": query,
            "max_expansions": 10
            }
          }
        },
        "size": 5,
        "from": 0,
        "_source": ["autocomplete_field"]
      }
    }).then(function(es_return) {
      deferred.resolve(es_return);
    }, function(error) {
      deferred.reject(error);
    });

    return deferred.promise;
  };

Below is the HTML code utilizing AngularJS UI Bootstrap:

<input type="text" name="q" ng-model="searchTerms" placeholder="Search" class="form-control input-lg" uib-typeahead="query for query in getSuggestions($viewValue)" typeahead-on-select="search($item)" typeahead-popup-template-url="customPopupTemplate.html" auto-focus>

The corresponding getSuggestions function in the controller looks like this:

    //get suggestions
  $scope.getSuggestions = function(query) {
  $scope.isSearching = true;
  return searchService.getSuggestions(query).then(function(es_return){
    var phrases = es_return.hits.hits;
    console.log(phrases);
    if (phrases) {
      return $scope.autocomplete.suggestions = phrases;
    };
    $scope.isSearching = false;
    });
};

When testing, I'm seeing 5 suggestions displayed in the dropdown menu but they all appear as [object Object]. This seems to be related to the line:

var phrases = es_return.hits.hits;

The console output shows:

[Object, Object, Object, Object, Object]

I need assistance in properly accessing the value of "autocomplete_field" within the _source object of the Elasticsearch results.

UPDATE The template used for the dropdown menu is:

<ul class="dropdown-menu" role="listbox">
    <li ng-repeat="match in matches track by $index" ng-class="{active: isActive($index) }"
      ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)" role="option" id="{{::match.id}}">
      <div uib-typeahead-match index="$index" match="match" query="query" template-url="templateUrl"></div>
    </li>
</ul>

UPDATE 2 Here's an example JSON response:

    {
   "took": 5,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 3,
      "max_score": 2.5897822,
      "hits": [
         {
            "_index": "autocomplete",
            "_type": "suggestions",
            "_id": "229",
            "_score": 2.5897822,
            "_source": {
               "autocomplete_field": "fast and furious"
            }
         },
         {
            "_index": "autocomplete",
            "_type": "suggestions",
            "_id": "230",
            "_score": 2.5897822,
            "_source": {
               "autocomplete_field": "die hard"
            }
         },
         {
            "_index": "autocomplete",
            "_type": "suggestions",
            "_id": "107",
            "_score": 1.7686365,
            "_source": {
               "autocomplete_field": "the bourne identity"
            }
         }
      }
   }

Answer №1

Upon reviewing the JSON layout, it is evident that a modification needs to be made to the uib-typeahead attribute. The correct adjustment should be as follows:

uib-typeahead="query as query._source.autocomplete_field for query in getSuggestions($viewValue)"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to including spinner in React JS with TypeScript

I need help with adding a spinner to a React component. The issue I'm facing is that the spinner does not disappear after fetching data from an API. Can someone please point out what I am doing wrong? Here is the code snippet: import React, { useSta ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

The div functions seem to stop working properly after they have been multiplied

Initially, I use JavaScript to multiply the div but then encounter issues with the function not working properly. function setDoorCount(count) { $('.doors').html(''); for (var i = 0; i < count; i++) { var content = " ...

Navigating through directories (including nested ones) containing images in React Native; what's the best way to approach this

I am currently attempting to organize groups of images. Within the directory ./assets, there are several folders structured as follows: ./assets ├── 1x3 │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── 3x3 ├── 1. ...

Creating a custom directive in AngularJS that utilizes an event listener

I am currently working on designing a custom directive that includes a text box. When a user clicks a button, the text box should expand and become focused. If the user then clicks away from the expanded text box, it should minimize, disappear, and display ...

Issue with adding a key:value pair to res.locals.object in Node/Express not functioning as expected

Currently, I am working on constructing an object within res.locals by executing multiple MongoDB operations and utilizing the next() middleware. Once I have added an object to res.locals, such as: res.locals.newObject, my goal is to subsequently add addi ...

Emphasize specific lines within a textarea

I am facing a challenge with a textarea dedicated to validating telephone numbers. My goal is to highlight the lines that contain invalid telephone numbers by adding two asterisks in front of them. However, I'm struggling to figure out how to highlig ...

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...

The `innerHTML` function is responsible for closing HTML

My switch structure is set up as follows: switch (ratio) { case "16:9": imgContainer.innerHTML = '<img src="images/test-rata-de-aspect.jpg">' break case "4:3": imgContainer.innerHTML = '<img src="image ...

Unable to trigger ng-click event in IE browser, while it functions properly in Chrome

<select id="from" multiple="multiple" name="list" ng-model="selectedVal"> <optgroup label= "{{geo.Geo}}" ng-repeat="geo in Geographies"> <option id="{{country.CountryKey}}" ng-repeat="country in geo.Country" ng-click="arrayPush( ...

Navigate to AngularJS page utilizing the specified :id value

In my AngularJS Application, I am using ngRoute for routing. While the routing works fine and redirects to the correct page with the right partial open, I am facing an issue in retrieving the necessary item on the second page. The first page allows users ...

Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks. Following guidance from this source, I successfully implemented syntax highlighting wit ...

What is the best method to modify the accurate phone number within my script?

I need help with a text format script. link HTML CODE: <label for="primary_phone">Primary Phone Number<span class="star">*</span></label> <br> <input type="text" name="primary_phone" id="primary_phone" class="_phone requ ...

Error encountered in React: Unable to access property of splice as it is undefined

As I am still getting acquainted with React/JS, I am currently navigating through the process of developing a mobile website. My main goal is to incorporate a delete function without the use of a button. My approach involves utilizing a long-press event, a ...

Email address string loses the '+"' when using AJAX

My ajax code has been working well in most cases, but when I tried using it for updating user details on my page, I noticed that the ""+"" symbol was getting lost if used in an email address (such as <a href="/cdn-cgi/l/email-protection" class ...

Steps for linking a keypress to trigger a specific action

I need help creating a script that will redirect to a URL when a button is clicked. Below is the code I have developed. HTML : <a id="#next" href="example.com">↵</a> <a id="#previous" href="example.com">↳</a> JS : $(document ...

Jquery Query: Is it possible to incorporate variables into CSS properties?

I manage a website that supports multiple languages, and I want to adjust the position of my container based on the selected language. To achieve this, I attempted the following code: prop = lang == 'ar' ? 'right' : 'left'; $ ...

JavaScript mouse and touch movement events (mousemove, pointermove, touchmove) are not always accurate

I'm currently working on developing a JavaScript whiteboard and have implemented the following code: let lastTimestamp = 0; const fps = 1000/60; document.addEventListener("pointermove", moveMouse, false); function moveMouse (e) { e.preve ...

Utilizing JavaScript for the removal or hiding of span elements with specific class attributes

I am currently working on a software project that involves compiling HTML fragments and then exporting them to Microsoft Word. My goal is to create a script that will cycle through these compiled fragments and remove specific tags that have a particular CS ...

Processing a JSON array of objects in AngularJS

When using Angular's fromJson function to parse a JSON string, I encountered an issue. If the JSON is a simple array like "[1, 2]", the code works fine. However, I need to work with an array of dictionaries instead. var str = "[{'title' ...