Associate the ng-model with ng-options value and label

I'm currently using ng-options to create a select tag that displays location options. The labels represent the location names, while the values indicate the corresponding location ID as stored in the database.

In addition to binding the value (location ID) to an ng-model attribute, I also wish to bind the label (location name) to a separate ng-model attribute. This separation is necessary since the id field will be sent via POST to a server that specifically expects this attribute. Can someone advise me on the optimal approach for accomplishing this task in Angular?

This section of my code illustrates the current implementation:

<div ng-app="app"><div ng-controller="edit">
  <select ng-model="purchase.pickUpLocationId" ng-options="loc.id as loc.name for loc in purchase.availableLocations"></select>

  <!-- At present, this model remains unbound: -->
  <p>Your selected location is {{ purchase.pickUpLocationName }}</p>

</div></div>

var app = angular.module('app', []);

app.controller('edit', ['$scope', function($scope) {
    $scope.purchase = {
        pickUpLocationId: 30,
        availableLocations: [
            {id: 20, name: "Charleston, SC"},
            {id: 30, name: "Atlanta, GA"},
            {id: 40, name: "Richmond, VA"},
        ]
    };
}]);

Answer №1

Make a change to the code below where you bind and reference the entire object. This will allow you to access the id later on for any desired action.

<select ng-model="selected" ng-options="loc as loc.name for loc in purchase.availableLocations"></select>

<p>You've chosen {{ selected.name }}</p>
<p>You also have an id! {{ selected.id }}</p>

Visit this JSFiddle link for more information

Answer №2

One recommendation is to start by representing it as a dictionary

{
   "35": "Chicago, IL",
   "45": "New York City, NY"
}

and then utilize

{{availableCities[purchase.locationId]}}

also establish ng-options like this:

<select ng-model="purchase.locationId" ng-options="id as label for (id, label) in purchase.availableCities"></select>

Answer №3

Updated scniro answer

<div ng-app="uniqueapp">
<div ng-controller="uniquectrl">
     <select ng-model="selectedlanguage" ng-options="option as option.language for option in uniqueresult.locales"></select>        
     <p>You have selected {{ selectedlanguage.language }}</p>
     <p>You also have an ID! {{ selectedlanguage.localeId }}</p>
     <p>
     </p>
     <input type="text" value="{{selectedlanguage.localeId}} : {{selectedlanguage.language}}" style="width:50%;"/>

</div>

JSFIDDLE -Binding options with unique values and labels

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

Preserve input values after form submission in <?php> code block

I would like to retain form values after submission. I have come across some techniques that claim to do just that: However, when I try to run the HTML file, I encounter two issues: firstly, the code does not function as intended and secondly, PHP snippet ...

Can you explain the concept of asynchronous in the context of Ajax?

Can you explain the concept of Asynchronous in Ajax? Additionally, how does Ajax determine when to retrieve data without constantly polling the server? ...

Flashing tilemap during the update process

I'm attempting to create a game map on a canvas using a JSON file produced by tiled map editor. I believe I am close to accomplishing this, but I encounter one issue. When I include the call to load the map in my update function, the map flickers on ...

Using AngularJS to apply conditional ngStyle

Can I achieve a similar effect to this using the following code: <span data-ng-style="vm.myFlag ? 'background-color:{{myObject.color}};padding:2px;border-radius:2px;' : ''"> The if-else statement in the above code does not work ...

Tips for utilizing a ForEach loop in JavaScript to create an object with dynamically provided keys and values

Looking to create a JavaScript object with the following structure, where the Car Make and Model Names are provided from other variables. { "Sedan":{ "Jaguar":[ "XF", "XJ" ], "AUDI":[ "A6", ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

I have been working on creating a horizontal menu, but encountered an issue where the nav tag is unable to accommodate all the ul lists within itself

My latest project involves a menu with three separate divs: logo, nav-bar, and right-bar. I decided to use justify-content: space-around to position the elements - the logo on the left, navigation in the center, and right-bar on the right. However, when I ...

Ways to trigger a Vue.js method after a delay of 500 milliseconds

Currently, I am developing a search system that triggers an ajax call with every key press. However, I would like to implement a delay of 500ms before the ajax call is made after typing begins. Any ideas on how this can be achieved? ...

Removing HTML tags and then reapplying HTML tags Part 1

Attempting to convert the following string: <p> string <b> bold <em>italic string</em> also(bold) </b> </p> to this modified string: <p> string </p> <!----------- ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

Obtain all text within a <div> element by utilizing the agility html package

When attempting to retrieve all <p> tags from within a <div> using the Agility HTML package, I encountered an issue where only the first <p> tag was obtained. <div id='bodayDiv'> <p> hi </p> <p> what is ...

Inquiring about how to make the pieces move on the checker boards I created

I'm having trouble getting my SVG pieces to move on the checkerboard. Can someone please help me figure out how to make them move, even if it's not a valid move? I just want to see them in motion! The important thing is that the pieces stay withi ...

When Selenium in JavaScript cannot locate a button element, use `console.log("text")` instead

I am trying to capture the error when there is no button element available by using console.log("No element"). However, my code is not working as expected. const {Builder, By} = require("selenium-webdriver"); let driver = new Builder().forBrowser("chrome ...

What is the best way to attach every sibling element to its adjacent sibling using jQuery?

I've been working with divs in Wordpress, where each div contains a ul element. <div class="list-item"> <div class="elimore_trim"> Lorem ipsum </div> <ul class="hyrra-forrad-size-list"> <li>Rent 1< ...

JavaScript: a highly effective method for verifying if a variable is a function, an array, or an object

Imagine a scenario where we have a variable that could potentially be a function, object, or array. I am in search of the most efficient method to determine its type. In my opinion, the current approach is not optimized because if I already know that isF ...

Setting up the current user's location when loading a map with Angular-google-maps

I am currently utilizing the library in conjunction with the IONIC framework. To manually set the center of the map, I have implemented the following code snippet: .controller('mainCtrl', function($scope) { $scope.map = { cen ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Using the jQuery method `fadeToggle` to handle the functionality of multiple buttons toggling hidden text

I am struggling to make fadeToggle work properly. I want to reveal text when clicking on another div. Since I plan to use this for multiple elements, I am looking for a smart and efficient way to handle them all. Here is my current attempt which does not ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...