In Angular Typeahead, the model is used as an identifier and the Text represents the name in the array object

I'm currently utilizing the Angular UI Typeahead directive available at this link. Can someone provide guidance on how to assign a model as an id and display text as a name in it? I have attempted the method below but encountered issues. Any suggestions on how to proceed would be greatly appreciated. Thank you.

Note : To test, please input either a or k into the code pen provided below.

CodePen Demo

JS Snippet

 var states=[{'id':1,'name':'Alabama'},{'id':2,'name':'Kansas'}]

HTML Structure

    <input name="states" id="states" type="text" placeholder="enter a state" ng-
model="selected" typeahead="a.id as a.name for a in states | filter:$viewValue" 
class="form-control">

Answer №1

When attempting to only include the selected state id in the ng-model, you encounter an issue where only the id of the selected state appears in the input field as the ng-model only contains the id value.

Instead of simply inserting the id into the ng-model, it is necessary to select the entire object. This way, when a state is chosen, the expression a as a.name will display only the name from it. You can then utilize selected.id to pass the state id whenever needed.

Markup

<div class="form-group">
  <label for="states">Search for US States</label>
  <pre>Model: {{selected | json}}</pre>
  <input name="states" id="states" type="text" 
     placeholder="enter a state" ng-model="selected" 
     typeahead="a as a.name for a in states | filter:$viewValue" 
     class="form-control">
</div>

Forked Codepen

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

How can I create an efficient chat system using Ajax and settimeout without causing excessive virtual memory usage?

I'm in the process of creating a chat application using AJAX that fetches data every second with setTimeout. I have drafted a basic code where there is a number that increments each second by the number retrieved from the PHP page2. Upon testing it on ...

Is it necessary to include a promise in the test when utilizing Chai as Promised?

Documentation provided by Chai as Promised indicates the following: Note: when using promise assertions, either return the promise or notify(done) must be used. Examples from the site demonstrate this concept: return doSomethingAsync().should.eventua ...

Can ajax requests be made without a web browser?

Currently, I am in the process of developing JavaScript tests using mocha and chutzpah, which means conducting all my tests without a browser. However, I have encountered an issue where all my AJAX calls are resulting in empty strings. Even when using the ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful. Here is ...

Neither setState() nor forceUpdate() trigger the rendering process

I am working with a basic React setup that resembles the following structure: index.js ReactDOM.render(<App />, document.getElementById('root')); App.js export default class App extends Component { constructor(props) { super ...

Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic: $request->validate([ 'firstname' => 'required', 'lastname' => 'required', 'username' => 'required|unique:us ...

Utilize the jQuery autocomplete UI Widget to trigger a select event on a dynamically generated row in a table

Currently, I have successfully implemented a jQuery autocomplete feature on the text input of a table data element called txtRow1. The data for this autocomplete is fetched remotely from a MySQL database and returned in JSON format as 'value' for ...

The Node.js server is failing to retrieve information from the AngularJS application

Having trouble reading data sent from an AngularJS client to the server via $http.post. Can't seem to figure out where I've made a mistake. var data = $.param({ id:$scope.user_id, }); alert(JSON.stringify(data)); $http.post('/getd ...

Display the message "Please complete all required fields" on the AngularJS href when the necessary fields have not been filled out

Is there a way to implement input validation so that when a user clicks on a href link without filling out the required input fields, they see a message prompting them to fill in the fields? I tried changing the href to a button and it worked, but that&apo ...

Error: The function $(...).maxlength is not recognized - error in the maxlength plugin counter

I have been attempting to implement the JQuery maxlength() function in a <textarea>, but I keep encountering an error in the firefox console. This is the code snippet: <script type="text/JavaScript"> $(function () { // some jquery ...

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

What is the best way to retrieve the value of this event in a React component?

Is there a way to retrieve the value of an input field? Typically, I would use event.target.value to do so. However, in this case, that method is not viable because the path of event.target leads me to an li element instead: This issue arises with a compo ...

Is it possible for the $.post function to overwrite variables within the parent function?

Recently, I delved into the world of JavaScript and my understanding is quite limited at this point. So, please bear with me as I learn :-) I am working on a basic booking system that saves dates and user IDs in MySQL. The system checks if a particular da ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

What could be preventing the background color from changing when attempting to use style.backgroundColor?

My objective is to store the current tab background color in a variable and then use that variable to change the body color. However, for some reason it is not working as expected. Can you help me figure out why? const tabName = 'someId'; var ...

Fetch data from Firestore when the page loads using the useEffect hook

Below is the simplified code snippet I am currently using: import { useState, useEffect, useContext } from 'react' import { useRouter } from 'next/router' import { firestore } from './firebase-config' import { getDoc, doc } f ...