Using AngularJS to dynamically populate a select list with options from a JSON

Trying to populate a select option with data from a simple JSON array.

For example, I want to create a country selector. Each country in the array has an ID and a name, among other fields that are not needed. Essentially, I aim to set one value in the value="" attribute and display another between the

<option>tags</option>

HTML Snippet

<div ng-controller="DemoCtrl">

  <p>populate select options with ajax</p>

    <select id="Country" name="Country" class="form-control" size="10" 
        ng-model ="chooseCountries">                                
            <option ng:repeat="country in chooseCountries" value="{{country.id}}">     
                {{country.name}}
            </option>
    </select>

</div>

Javascript Snippet

'use strict';

function DemoSelectCtrl($scope) {

    $scope.chooseCountries=[
        {countryId : 1, name : "France - Mainland", desc: "some description" },
        {countryId : 3, name : "Gibraltar", desc: "some description"},
        {countryId : 3, name : "Malta", desc: "some description"}
    ];  

});

I have combined everything in this JSFiddle. However, I feel like something is missing.

Answer №2

If you look at the example above, you will notice that the value attribute is missing. To fix this, simply change it to value="{{country.countryId}}". Give it a try!

<select id="Country" name="Country" class="form-control" size="10" ng-model ="chooseCountries">                                
    <option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
        {{country.name}}
    </option>
</select>

For a visual representation, check out the example here.

Answer №3

There is a mistake in the value attribute, it should be corrected to country.countryId.

Additionally, ensure that the ng-model directive is set to a single countryId value (or an array of country IDs) rather than the entire object.

<select id="Country" name="Country" ng-model ="selectedValue"> 
    <option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
        ...   

JS:

function DemoSelectCtrl($scope) {

    $scope.selectedValue = 1;    

    $scope.chooseCountries=[
        {countryId : 1, name : "France - Mainland", desc: "some description" },
        {countryId : 3, name : "Gibraltar", desc: "some description"},
        {countryId : 3, name : "Malta", desc: "some description"}
    ];  

});

Answer №4

If you're looking to populate a standard select input with objects, one effective method is to utilize the "ng-options" directive and "ng-repeat" with a "track by id" approach. You can also consider using angular-ui-select if preferred. This technique works seamlessly with ng-model. Here's an example:

<select id="select_field" name="select_field"
   ng-model="vm.selectedCountry"
   ng-options="country as country.name for country in vm.chooseCountries track by country.countryId">
   <option value="">-- Select Country --</option>
</select>

Note that when utilizing "vm," it typically refers to the controllerAs alias defined within the controller. If you are directly using $scope, the "vm" can be omitted.

This method has proven to be highly effective in populating select fields with objects.

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

Challenges with API arrays

Here is the response from the API: { "meals": [ { "strTags":"Fish,Breakfast,DateNight", } ] } I am aiming to achieve the following outcome: https://i.sstatic.net/Y7B8B.png This is my current code setup: &l ...

Tips for using a MixedId field and an ObjectId field together in Mongoose join functionality

I have a scenario where I am using join for 2 schemas, outlined below: var mongoose = require('mongoose'), Schema = mongoose.Schema; var CompanySchema = new Schema({ name: String, address: String, address2: String, url: String, ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

Save the libxmljs XML data into a file

Currently, I have a libxmljs XML object that I need to save to a file. Here is what I have so far: const libxml = require('libxmljs'); const xmlString = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>&apo ...

Unable to load connected modules from npm/yarn link within the WSL environment

Trying to import a local dependency into my project is proving to be quite challenging. The situation at hand involves a project named 'test_project' and another one called 'test_module'. Linking test module to the global node_modules ...

Insert within a canvas

Although there is a previous inquiry on this topic, it appears to be outdated. Despite searching through dartlang's resources and conducting online research, I have yet to find a solution to the issue at hand. document.onPaste.listen((e) { ...

Encountered a session.socket.io error: unable to find session using the provided key: connect.sid

So, I've been struggling with an issue for the past couple of days and I can't seem to figure it out. I've searched through various resources like this GitHub issue and Stack Overflow, but I still haven't found a solution. Here's m ...

Populate vue-multiselect with links from the router

Is there a way to populate the vue-multiselect dropdown with <router-link> options? Typically, router links are defined declaratively in the <template>, but vue-multiselect relies on binding an array of options. Any suggestions on how to approa ...

Extracting an extension from a file name containing special characters in JavaScript: A step-by-step guide

I am attempting to extract the file extension from a filename. The filename may incorporate special characters such as "#, @, ., _, (), etc. For example: var file1 = "fake.der" var file2 = "fake.1.der" var file3 = "fake_test.3.der" In the scenarios above ...

Developing a server-side checkbox feature and implementing a corresponding JavaScript function

After dynamically creating a checkbox on the server-side and populating it in a table on the webpage, I want to utilize it to trigger some JavaScript functions on the client side. However, I'm unsure of how to activate the function using a checkbox c ...

Identifying latency and throughput in Flink streaming applications

I'm currently setting up a Flink streaming job and I need to measure the throughput and latency of the streaming process. I've got my Kafka broker server running and messages are coming in from Kafka. How can I calculate the number of messages pe ...

Avoid parsing HTML tags when retrieving data from Walmart's open APIs

Is it possible to receive a response from Walmart open APIs without escaped HTML tags? For example, when using the search API, here is a sample response: { "query": "ipod", "sort": "relevance", "responseGroup": "base", "totalResults": 257 ...

An error was encountered: Component.setState is undefined and cannot be read, leading to a TypeError

Could the error be caused by the fact that the Counter component remains at a count of 0, with this not bound anywhere? class Counter extends React.Component { constructor(props) { super(props) this.state = { count: 0 ...

Max call stack size exceeded error encountered and logged without catching

While attempting to display multiple markers on a Google map within the Ionic framework, I encountered an Uncaught RangeError: Maximum call stack size exceeded error message in the log. The issue seems to be related to the Cordova Google plugin that I am ...

Mistake in my API response using Retrofit for fetching Call List

After trying to retrieve a list of players, I received a response for Call > 3 Players but in a peculiar format. Unable to identify the error, I spent 5 hours searching without any luck. ApiClient.class: import com.google.gson.Gson; import com.google. ...

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Clean up HTML with jQuery or JavaScript

I have a small HTML-WYSIWYG editor on my CMS and I'm curious if there is a reliable script available for cleaning up HTML on the client-side. I often encounter issues with HTML copied from Microsoft Word. Maybe using some regex could solve this proble ...

Identifying memory leaks in Javascript

I've developed a basic script to retrieve the size of a list in redis and display memory usage. It appears that the amount of "heap used" memory is gradually increasing. Could this indicate a memory leak, and what modifications can be made to preven ...

json keys with spaces

I need help with a JSON structure I am working with: data: { First Name: "Robert", Last Name: "Smith" } I'm trying to access the data using javascript like this: "data.First Name" I know this is incorrect syntax. How can I extract the information fr ...