Choosing an id of my preference to set as the value in the ng-options select list and ensuring proper binding with ng-model

When using Angular, I am trying to create a select list where the value corresponds to the actual id of an object. I want to bind this correctly with the ng-model directive.

Here is my attempt:

<select ng-model="selectedPersonId"                 
ng-options="p.id as p.name for p in People track by p.id"></select>

$scope.People = [
    { name : "Fred", id : 1 },
    { name : "Joe", id : 2 },
    { name : "Sandra", id : 3 },
    { name : "Kacey", id : 4 },
    { name : "Bart", id : 5 }
];

$scope.setTo1 = function(){
    $scope.selectedPersonId = 1;
}

http://jsfiddle.net/b7dyadnr/

In this select option, the value matches the correct id (id of the person in people) and the text is accurate. However, the binding does not work. Setting the value of $scope.selectedPersonId does not reflect in the selection on the list.

I have found a workaround:

<select ng-model="selectedPersonId"                 
ng-options="p.id as p.name for p in People"></select>

http://jsfiddle.net/rgtbn2f5/

This method works, where setting $scope.selectedPersonId reflects changes on the list. But in this case, the id used in the select option value is not the actual id of the person!

<option value="0">Fred</option> <!--option value is 0, not Fred's true id -->
<option value="1" selected="selected">Joe</option>
...

My goal is to use it like the first example while still having Angular use the true id of the person in the select option value, rather than an index or other identifier.

If you're wondering why I need it to work this way, it's because the id is sent to an API and the model can be set via query string, so it must work with these requirements.

Answer №1

Encountered a similar issue before. It seems that using p.id only works in either the select or the trackexpr. The workaround that worked for me (setting the value to id) was like this:

<select 
ng-model="selectedPerson"                 
ng-options="p as p.name for p in People track by p.id"></select>

However, selecting a person with id = 1 required a somewhat cumbersome code:

$scope.setTo1 = function () {
    $scope.selectedPerson = $scope.People.filter(function (item) {
        return item.id == 1
    })[0];
}

Here is a link to the jsfiddle.

This is because you need to assign ng-model the same item from ng-options collection since they are compared by reference. Angular's documentation states:

Note: ngModel compares by reference, not value. This is important when binding to an array of objects. See an example in this jsfiddle.

In the end, I decided to let Angular handle setting the option value as needed, allowing me to simply do: $scope.selectedPersonId = 1

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 retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Click-o-Meter: Tracking Button Presses

I’m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet: <?php $counterFile = 'path/to/counter.txt' ; ...

"Unlock the power of Meteor: dynamically serve up the specific range of items

I am facing a challenge with my vast collection of over 5000+ records. I aim to display the records in groups of 10 for easier viewing. How can I update the data dynamically to achieve this? Here is what I have attempted so far: In my server.js file : M ...

What is the best way to import two components with the same name from different libraries?

How can I import the Tooltip component from two different libraries without encountering naming conflicts? For example: import { Tooltip as LeafletTooltip } from "react-leaflet"; import { Tooltip as RechartsTooltip } from "recharts"; By renaming the impo ...

How to customize the button color in a Next.js application

Help Needed: Issue with Changing Default Button Color in Next.JS Web Application. The button text color appears as grey on Desktop Google Chrome, but shows up as blue on Mobile Chrome browser. I want to unify the color to be grey on both platforms. Custo ...

Why does my value always revert to 0 whenever I switch screens while utilizing async storage?

Utilizing a stack Navigator, my primary screen is tracker.js, and the secondary one is macros.js. In macros.js, I have the ability to manually input nutritional macros (calories, Fats, Carbs, Protein) and add them to my UsedDailyCalories. However, when I ...

Adjust the font size to fit within the container

My webpage features a bootstrap 4 container with three columns that adjust on screen sizes above the md breakpoint (col-md-4). Each column contains an img with the class img-fluid, and when hovered over, text description appears. I want this hover text to ...

Encountered an issue during the creation of a Nuxt.js project using the command line tool, where a SyntaxError was triggered

I encountered an issue while attempting to set up a nuxt.js starter project using the nuxt cli. Here are the steps I followed: Installed vue cli globally with the command: npm install -g vue-cli Created the project using: vue init nuxt-community/star ...

Unable to modify headers after they have already been sent to the client - an error has occurred

I am encountering an issue when trying to redirect the page to another page. Everything works fine with the first post request, but starting from the second one, I keep getting this error message: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t ...

Unable to transmit information back to React

Recently stepping into the world of React and Node.js, I have successfully created a function in my Node.js application that executes a Python script using child process. However, I seem to be facing a challenge with my router post method named pythonExecu ...

Error: Attempting to display API data in a CardView using NativeScript-Vue results in a TypeError stating that property 'endpoint_link_1' is undefined

Greetings, I am a beginner in NativeScript-Vue and JavaScript. I do not have extensive experience with heavy Javascript coding. I am facing an issue with displaying data fetched from an API in CardViews. Below is the code snippet I attempted: <template ...

Guide to saving output to a file using node.js and express

I have developed an application using node.js and express.js on top of elasticsearch. The application is quite simple, featuring a search box that returns results in JSON format when querying for a specific keyword. For example, searching for the word "whi ...

What are the steps for running app.js deployed on a remote server using the local bash terminal?

After launching my web application on GoDaddy, which is built in Node.js, I have encountered a dilemma. In order to run app.js, I currently rely on my computer's bash command prompt. However, this poses an issue - if I were to shut down my laptop, the ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

Creating a Three.js 3D Text Effect with Layers of Letters

Why are my 3D text letters overlapping in the threejs TextGeometry when viewed from an angle? https://i.sstatic.net/W0ocu.png See the code snippet below: class MyScene { // Code for handling Three.js scene and elements constructor(elementSelector ...

Stripping quotation marks from CSV information using Javascript

After performing a fetch request using JavaScript, I have converted JSON data into CSV format. datetime","open","high","low","close","volume" "2020-01-28","312.48999","318.39999","312.19000","317.69000","31027981" "2020-01-27","309.89999","311.76001","30 ...

Hide the menu when a user clicks on any of its options

On a next.js website, there is a hidden panel that slides out from the edge when a button is clicked. Inside the panel, there is a menu. The panel and the menu are separate components. The goal is to have the panel open and close when the button is clicked ...

Is it possible to trigger JavaScript after loading a page in jqTouch with AJAX?

Similar to the kitchensink demo, I have successfully used jqtouch to call external .html pages into the index page. One of these external pages contains a video that is being played using sublime player. Everything is pretty basic so far, but my challenge ...

Ways to showcase Switch/Case in two separate drop-down menus

I'm currently working on a PHP file with a switch/case structure that I believe is in JSON format. While I may not be an expert in PHP, AJAX, and JSON, I'm really putting effort to learn more about it. <?php switch($_GET['make'] ...