How can I extract specific data from a JSON response and populate a select dropdown with AngularJS?

My current project involves making an http.get request to fetch a list of airports. The JSON response is packed with information, presenting a series of objects in the format shown below

{"id":"1","name":"Goroka","city":"Goroka","country":"Papua New Guinea","iata":"GKA","icao":"AYGA","latitude":"-6.081689","longitude":"145.391881","altitude":"5282","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"}

The task at hand is to extract the country and IATA code from this data and showcase them within a select element on my HTML page as demonstrated below

Papua New Guinea GKA
Greenland UAK ...

I've managed to generate an array of objects containing these specific details (in a factory function) and have subsequently passed it back into my array. However, I'm currently grappling with how to exhibit two distinct pieces of data in a select element.

Answer №1

To effectively display data in a dropdown menu, utilize the ng-options directive within the select element.

If your data array consists of objects with structure like this:

$scope.airports = [{id:1,name:"Papa New Guinea",iata: "GKA"},...]

You can present them in a select field as shown below:

<select ng-model="selectedAirport" ng-options="(itm.name + ' ' + itm.iata) for itm in airports"></select>

For a functioning example, refer to this plunkr

Answer №2

If you're looking to implement the ng-options directive for applying ng-repeat functionality on a select element in AngularJS, check out the documentation here: https://docs.angularjs.org/api/ng/directive/ngOptions. For instance, if your array of airports can be fetched synchronously, you can do so in your controller:

module.controller('ctrl', function($scope, Airports) {
    $scope.airports = Airports.get();
    $scope.$watch('airportId', function(newValue) {
        console.log(newValue);
    });
});

In your template, make use of Angular's expression parsing like this:

<select ng-options="for item in airports" ng-model="airportId">
    <option value="item.id" ng-bind="item.country + ' ' + item.iata"></option>
</select>

Alternatively, display the values directly within the option tag:

<select ng-options="for item in airports" ng-model="airportId">
    <option value="item.id">{{item.country}} {{item.iata}}</option>
</select>

Answer №3

To combine the properties together:

<div ng-app="myApp">
            <div ng-controller="myCtrl">

                <select ng-model="model.id" ng-options='note.id as (note.name+" "+note.iata) for note in notes' ></select>

                {{model.iata}}

            </div>

        </div>

https://jsfiddle.net/7eqsc/146/

Answer №4

To display specific data from a JSON object without the need to clear it, you can utilize the ng-options directive in AngularJS:

<body ng-app="selectExample">
  <script>
    angular.module('selectExample', [])
      .controller('AirportController', ['$scope', function($scope) {
        $scope.airports = [{
          "id": "1",
          "name": "Goroka",
          "city": "Goroka",
          "country": "Papua New Guinea",
          "iata": "GKA",
          "icao": "AYGA",
          "latitude": "-6.081689",
          "longitude": "145.391881",
          "altitude": "5282",
          "timezone": "10",
          "dst": "U",
          "tz": "Pacific/Port_Moresby"
        }, {
          "id": "2",
          "name": "RAF Cranwell",
          "city": "Coningsby",
          "country": "Lincolhshire",
          "iata": "QCY",
          "icao": "EGXC",
          "latitude": "",
          "longitude": "",
          "altitude": "",
          "timezone": "10",
          "dst": "U",
          "tz": ""
        }];
      }]);
  </script>
  <div ng-controller="AirportController">

    <label>Select Airport:
      <select ng-model="selectedAirport" ng-options="airport.name + ' - ' + airport.iata for airport in airports"></select>
    </label>
    <pre>
        {{selectedAirport}}
    </pre>
    <br/>
  </div>
</body>

Click here to view the code in action

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

Modify section background color for every iteration in an image carousel

Is it possible to dynamically change the background color of the cd-hero section each time a new image is loaded in a simple slider on the home page? Can this be achieved by storing predefined colors in an array so that different images trigger different b ...

A distinct handler function designed for a dynamically generated form

I have 3 MaterialUI TextFields that are rendered n number of times based on user input (stored in a variable named groupMembersCount) in a functional ReactJS component using the useState hook: const [groupDetails, setGroupDetails] = React.useState([ { ...

Warning: React detects a missing dependency within an interval in the effect

A webpage I developed using React and Next.js has the following structure. import Head from 'next/head'; import { useEffect, useState } from 'react'; import Header from '../components/Header'; export default function Home() { ...

AngularJS's $http.get function has the ability to read text files, but it struggles with reading JSON

I'm new to angularjs and I am struggling to retrieve data from a json file using the $http.get method. It seems to work fine when I try to read a simple txt file, but not with the json file. I can't seem to pinpoint where the issue lies... Belo ...

Exploring scope in an angular service

My goal is to show a success message after clicking a button. Since I need this functionality in multiple controllers, I decided to implement it using a service. However, I am facing issues accessing the scope. index.html <div ng-controller="uploadCon ...

Using JavaScript/jQuery to tally characters

Here is the code snippet that I am currently working with: PHP <input style="color:red;font-size:12pt;font-style:italic;" readonly="" type="text" name="q22length" size="3" maxlength="3" value="50"/> <textarea onkeydown="textCounter(doc ...

What steps should I take to ensure the privacy of this React Layout?

To ensure only authenticated users can access the layout component, we need to implement a check. const router = createBrowserRouter([ { path: "/", element: <Layout />, children: [ { path: "/", ...

What is the procedure for utilizing Javascript to redirect a user on a website back to the login page if necessary?

Is there a way to redirect a website user back to the login page if they try to access a secure page without logging in first? I'm looking to implement this using JavaScript and cookies. Any suggestions or ideas on how to achieve this seamlessly for t ...

What is the best way to transfer $scope to a service in angular.js?

I have two services listed below. When navigating to a specific URL, I need to resolve "OtherService.promise". However, for certain routes, I would prefer to utilize a scope variable within the AppService method instead of the promise. How can I make thi ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

Transferring an array from PHP to Javascript using GET method

Can someone help me figure out how to pass an array to Javascript after it sends a GET request to PHP? I've got the data sending and retrieving down pat, but now I'm stuck on how to send the data back as an array. Here's what I have so far: ...

Provide JSON data on a designated pathway

I'm currently working on setting up a basic API that will respond with JSON data when accessed at the path /json The goal is to send back the object {"message": "Hello json"} in JSON format whenever a GET request is made to the /j ...

Learn how to effectively utilize templateURL in an express and angular project

Our project utilizes Express without any view engine. To set up static directories, we have the following: app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/view')); app.use(express.static(__dirname + ...

Encountering an ongoing problem with trial repetition in JsPsych, which is causing the looping to continue endlessly without

As a beginner in JsPsych, I'm diving into creating a basic math quiz task to sharpen my skills. The goal is to generate random math questions as prompts and stop the task after 10 correct answers. I've managed to code that selects random math pro ...

Discovering the most cost-effective combination algorithm

Looking for two numbers, P and Q, in a given array N with at least 5 items where 0 < P < Q < N - 1. Consider the following array: const N = [1, 9, 4, 5, 8]; If P = 1 , Q = 2 , then the cost is N[P] + N[Q] = N[1] + N[2] = 9 + 4 = 13 If P = 1, Q ...

Error: The application encountered an issue while trying to initialize the module

Forgive me for asking, but I have searched many topics with the same name and they didn't help. It seems like everyone has their own specific code. var app = angular.module('iop', []); // Setting up the service factory to create our ...

Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template: <body ng-controller="myCtrl"> {{loadDataSubject('${subjectList}')}} {{loadDataTopic('${topicList}')}} <h1 class = "bg-success" style="color: red;text-align: ...

Implementing a delete functionality within a loop on a JavaScript object array

I have a JavaScript object with the following structure: var partner = { p_name: { value: partner_name, label: "Name" }, p_id: { value: partner_ID, label: "ID" }, p_status: { value: partner_status, label: "Status" }, p_email: { value: partner_emai ...

Checking if the iframe location has been modified using Jquery

Looking to determine if the location of an iframe has been modified. function checkLocation() { setInterval(function(){alert("Hello")},3000); if (document.getElementById("myiframe").src = 'http://www.constant-creative.com/login';) { } ...

Is it possible to retrieve the pixel color of a mesh by clicking on it in JavaScript?

On the current page, we have a mesh loaded with TreeJS and displayed in a canvas: https://i.sstatic.net/j8Ztj.png Is there a way to retrieve the color of the point where a click occurs? I attempted a method suggested in this thread: Getting the color val ...