How to Retrieve the Selected Value from an Array of Objects using Angular UI Typeahead

I am currently utilizing the typeahead angular bootstrap directive, which I find to be quite useful. However, I am facing a challenge regarding obtaining the select value when using it with an array of objects (which is necessary for a custom template). The issue arises where I cannot retrieve the typeahead selection value – while it displays correctly, it is passed as [object object] to the target controller.

Here is the form in question:

<form ng-submit="startSearch(search.term , false, true)" novalidate>
<input typeahead-editable="true" typeahead="item as label(item) for item in startSearch($viewValue, true)| limitTo:10"
 required type="text" class="searchInput"  ng-model="search.term"
 typeahead-template-url="views/search/typeahead.html"   /> <!--| filter:$viewValue   typeahead-on-select="goState(selectState(select), label(select)"-->
<button class="searchBT" ng-submit="startSearch(search.term , false, true)"><i class="icon-search"></i></button>

Here is the relevant part of the controller:

$scope.search = {};
        $scope.startSearch = function(term, suggest, submitted){
            var deferred = $q.defer();
            if (submitted) {
                console.log($scope.search)
                $state.go('search.home',{'term':  $scope.search.term }); //term gets [object object] instead of the displayed name
            } else {
                    searchService.doSearch(term, suggest).then(function(data){
                        "use strict";
//                        console.log('data',data)
                        if (suggest){
                           deferred.resolve(data)
                        }
                    }, function(err){
                        "use strict";
                        $log.debug('err',err);
                    })
            }
            return deferred.promise;
        }

        };

        $scope.label = function(item){
            "use strict";
            //select label
            if (!item) {
                return;
            }


            return  item.symbol || (item.first_name +" " + item.last_name)
        }

In summary of my issue:

Although I receive a correct displayed value from the typeahead select list, it appears that the model (search.term) does not update properly and I end up with a [object object] result. Interestingly, if I manually input a value in the field and submit, I obtain the correct value along with the expected state transition.

To complicate matters further, the list contains various types of objects, so I need to apply certain logic regarding the objects through a function/filter rather than simply extracting a field.

Thank you for your assistance!

Answer №1

It seems like the issue might be that a property name is missing from the object. I've created a plunk demonstrating your code here. In this example, I've simplified the service calls to use a hardcoded array.

Make sure to take note of the object returned having both "Value" and "Text" properties.

var results = [];
angular.forEach([{Val: 1, Text: "AngularJS"}, {Val: 2, Text: "EmberJS"}, {Val: 3, Text: "KnockoutJS"}], function(item){
  if (item.Text.toLowerCase().indexOf(term.toLowerCase()) > -1) {
    results.push(item);
  }
});
return results;

Also, pay attention to how the "typeahead" attribute in the markup is populated with the actual text property of the object:

typeahead="item.Text for item in startSearch($viewValue)| limitTo:10"

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

Is the original image source revealed when clicked?

I've implemented an expand and collapse feature using jQuery/JavaScript. Clicking on the DIV causes the image inside to change state. However, clicking on the same DIV again doesn't return the image to its original state; it remains stuck in the ...

Comparing json results from ng-repeat against an array

Currently, I am working with a JSON result that appears in an ng-repeat and I want to filter it based on separate data objects or arrays: Controller.js $scope.jsonResult = [ { "id": "a123" }, { "id": "b456" } ] HTML <span ng-repeat="r in js ...

Sharing data from a Provider to a function in React can be done through various methods

After developing an NPM library that contains various utility functions, including one for calling endpoints, I encountered a roadblock when trying to set the Axios.create instance globally. Initially, my idea was to create a Provider and establish a cont ...

What causes the updated value to be appended to an array when using the spread operator to modify an existing property's value?

In my state, I have an array of objects: const initialState=[{a:1},{b:2},{c:{d:3}}] const [state,setState]=useState(initialState) My goal is to modify the value of b to 5 within my event handler: function changeBToFive() { setState((state) => [ ...

Ways to speed up the disappearance of error messages

There is a minor issue that I find quite annoying. The validation error message takes too long (approximately 3 seconds) to disappear after a valid input has been entered. Let me give you an example. https://i.sstatic.net/8UKrm.png Do you have any tips o ...

Using .htaccess for a 301 Redirect

I am currently working on setting up 301 redirects, and regardless of whether I implement the redirect in .htaccess or use a meta or javascript redirect, they all seem to be working. However, there is an issue where the old URL or directory is being append ...

What could be preventing this src tag from loading the image?

Here is the file structure of my react project Within navbar.js, I am encountering an issue where the brand image fails to load from the Assets/images directory. import '../../Assets/Css/Navbar.css'; import image from '../../Assets/Images/a ...

"An issue with ng-controller in AngularJS causing a simple error

Currently, I'm in the process of learning angularJS. While ng-app and ng-model are functioning properly, I've encountered an issue with ng-controller. Despite my efforts, I can't seem to pinpoint where I've gone wrong. My code isn' ...

A situation where the event onclick fails to occur within NextJS

index.js: function Home () { return <div> <html> <head> <title>Site</title> </head> <body> <div class= 'v5_3' onclick = "func_click()"></div> </b ...

A guide to connecting keyboard events to div elements within a React application

Currently working on a basic react project to gain some practical experience with the library. I aim to develop a simple user interface with blank spaces to be filled in by typing via keyboard input. Here's a glimpse of my progress so far: function ...

`Is it necessary to handle textStatus when encountering an HTTP error during an AJAX request?`

When utilizing jQuery and encountering an AJAX request failure attributed to an HTTP error (e.g., 500 Internal Server Error), what exactly is the assigned value of the textStatus parameter within the error handler function? For instance, $.ajax(...).fail( ...

Can you display a popup on a leaflet map from beyond its boundaries?

Utilizing leaflet maps, I have implemented a functionality where clicking on the map opens a popup at a specified location and centers on that position. The code for this is as follows: var popup = L.popup(); function onMapClick(e) { popup . ...

Tips for displaying identical tab content across various tabs using jquery or javascript

For instance, if we have tabs labeled as 1, 2, 3, 4, and 5, and a user has selected tabs 2, 3, and 4, how can we display the same content for those tabs while showing different content for the remaining ones? ...

JQuery error displaying [object Object]

I'm currently working on a calendar project where I have created a page to display events scheduled for a specific day. To ensure a seamless user experience without the need to reload the page every time a new event is added, I am utilizing Ajax. Us ...

Deactivate the typeahead function in the Angular controller based on the user's preference

Is there a way to disable Angular's typeahead feature when a user has a specific checkbox checked in the settings menu (with id = searchSuggestions)? The code provided below seems to work only on a fresh page reload, but not during an active session. ...

Toggle the visibility of a component in React by managing its state

Currently, I am faced with the challenge of toggling the visibility of a component based on a state value: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Button from ' ...

I'm curious why I can only see the HTML code and not the three.js code as well

I attempted to run a sample three.js game today, but only the HTML code appeared. I've also installed three.js with npm and tried running it with the VSC Live Server, but it's not working. You can find the source code here. What should be my nex ...

Display data from a PHP array in a JavaScript alert box

Within my Wordpress registration form, I am attempting to display the $error array in an alert message. I have experimented with using console.log(), but it does not show any output. Even when using JSON.stringify(), the alert only displays the word: true ...

I attempted to craft a toggle button by applying and removing an active class that I had previously designed, but unfortunately, it did not function as intended

Every time I click on a button, I keep encountering this error message. I am certain that my selector is correct, but I can't seem to figure out why I'm getting the Uncaught TypeError: Cannot read property 'classList' of undefined at HT ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...