Guide for populating select dropdown from Json file in Angular

As a newcomer to Angular, I am encountering some difficulties when attempting to bind values from a JSON file into a select form. Despite trying various solutions I found online, I am still unable to display anything. I am able to successfully retrieve the JSON file using $http.get, store it in a variable, and access its elements individually without any issues, which indicates that the file is being fetched correctly. The JSON data structure is as follows:

{
"regioni": [
    {
        "province": [
            {
                "code": "CH", 
                "comuni": [
                    {
                        "code": "069001", 
                        "cap": "66040", 
                        "nome": "Altino"
                    }, 
                    {
                        "code": "069002", 
                        "cap": "66044", 
                        "nome": "Archi"
                    } 
     ], 
                "nome": "Chieti"
            }
   ], 
        "nome": "Abruzzo"
    }
 ]
} 

Within the array of regions, each item contains a property nome and an array called province, which comprises properties like code, nome, and another array called comuni consisting of code, cap, and nome. My goal is to display the names of all comuni from all province. The controller function looks like this:

var app = angular.module("myCreation",[]);
app.controller("myStructureCtrl",['$scope','$http',function($scope,$http){
var comuniList = null;

 $http.get('/resources/italia_comuni.json')
     .then(function(response){
        comuni = response.data;
  });

}]);

The corresponding HTML code is:

<div id='selectCity'  style='width:30%;margin-top: 60px'>
        <label for='city'>Select a city</label> 
        <select name="city" id='city' ng-model="data.city" ng-options="regioni.province.comuni.nome for city in comuniList">
        </select> 
    </div>

I am uncertain about the exact way to retrieve and display the desired value, but I am hopeful that the current setup will work. Any guidance on this matter would be greatly appreciated. Thank you in advance.

Answer №1

Initially, the $http response populates the region data in the regioni variable as shown below:

 $http.get('/resources/italia_comuni.json')
 .then(function(response){
    $scope.regioni = response.data;
 });

Next, the ng-options should be set up like this:

ng-options="c.nome for c in regioni[0].province[0].comuni"

For further reference, please refer to this link http://plnkr.co/edit/abcd1234EFGH5678?p=preview

Answer №2

Absolutely, as mentioned by younes sofiane, utilizing $scope.regioni instead of a standard javascript variable is the key to effectively leveraging the response.

Consider the following example:

var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
  $scope.greeting = 'Hello!';
}]);

Here is the corresponding HTML:

<div ng-controller="GreetingController">
  {{ greeting }}
</div>

For a more comprehensive understanding, refer to the angular developer guide on the fundamentals: https://docs.angularjs.org/guide/controller

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

What steps can be taken to resolve the error message "Module '../home/featuredRooms' cannot be found, or its corresponding type declarations"?

Upon deploying my site to Netlify or Vercel, I encountered a strange error. The project runs smoothly on my computer but seems to have issues when deployed. I am using TypeScript with Next.js and even attempted renaming folders to lowercase. Feel free to ...

Discover the worth chart with JQ

I have a large JSON file that requires transforming some values based on a specific mapping. The current data structure is as follows: [ {"id":1, "value":"yes"}, {"id":2, "value":"no"}, {"id":3, "value":"maybe"} ] I aim to convert it into th ...

What is the best way to show personalized messages to users using modal windows?

Encountering bugs while trying to implement user messages in modals. function displayMessage(title, description) { var myModalErrorMessage; $("#customErrorMessageTitle").text(title) $("#customErrorMessageDescription").html(description) myModalEr ...

Style your Checkbox Button with the Checkbox component from Element Plus

Currently, I am utilizing Vue 3 along with the Element Plus library. My goal is to modify the hover, active, and select colors of the Checkbox Button that I have implemented. Unfortunately, my attempts to do so have not been successful. I essentially copie ...

Can you please guide me on retrieving information from an API using HTML, CSS, and JavaScript?

My task is to develop a web application using HTML, CSS, and JS with the following functionality: Retrieve a list of users from this API: https://jsonplaceholder.typicode.com/users. Upon clicking on a user, show a list of albums associated with that user ...

Error encountered: "Jest error - TypeError: Unable to access property 'preventDefault' because it is undefined."

I encountered an issue while testing the function below, resulting in the error mentioned above. function toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { ...

Getting attribute values from custom tags in AngularJS is a common task that can be

I am new to AngularJS and I'm having trouble with my code. I am attempting to retrieve the attribute value of post-id from my index.html file and display it in the console from my controller. Here is a snippet from my index.html: <post-creator po ...

Displaying data stored in a database using JSON format with Ember

I seem to be facing a challenge once again. Let me elaborate on what I am trying to achieve. Within the teammembers template, I aim to display information about Team Members and their details from a specific team by joining 3 tables. Here is an example o ...

The chrome extension is not displaying any output in the console, even though there are no errors

https://i.sstatic.net/YhEKl.png I am currently working on creating a browser extension that will monitor the xhr section of the devtools network tab. To start off, I have kept my background script as simple as possible. Even though there are no errors whe ...

Error alert: Controllers and services within the same module are experiencing injection issues

I'm in the process of creating an angular module that contains controllers and a service all within the same module. The issue I'm facing is an unknown provider error Error: $injector:unpr. I have made sure not to redefine the module multiple tim ...

Experiencing a DNS error while running a JavaScript script using Node.js

const { Client, EmbedBuilder, GatewayIntentBits, Collection, Events, Partials } = require("discord.js"); require("dotenv").config(); const { Guilds, GuildMembers, GuildMessages } = GatewayIntentBits; const { User, Message, GuildMember, ...

"Need help with displaying dates in a Material-UI table in ReactJS? Learn how to easily convert a date object to

When working with the DatePicker in material-ui, it generates date Objects. However, I want to display the selected value in a table. To achieve this, I need to convert the Object to a string since it is not possible to pass an Object directly to a table c ...

What are some methods for creating a tooltip or a similar quick information pop-up that appears instantly when hovered over?

I'm familiar with creating a basic tooltip by utilizing title="here's a tooltip", but I'm interested in having it appear instantly upon hovering instead of the usual delay. Is it feasible to achieve this using different tools such ...

Substitute link with asynchronous JavaScript and XML

I need to enable/disable user accounts by clicking on an anchor. The list of users is created dynamically using a loop. Here's an example of an anchor tag: <a href="http://www.example.com/users/deactivate/44" class="btn btn-success" title="Deactiv ...

Can you explain NodeSource in simple terms, and what purpose does it serve?

Not too long ago, I delved into researching how to effectively host a MEAN stack web application on AWS. During my quest for knowledge, I stumbled upon a tutorial that caught my eye. The one I ended up following can be found at https://www.youtube.com/wat ...

Converting a SQLite database to JSON using Haskell

How can I export a SQLite database to a JSON file in Haskell? Most other questions involve parsing JSON and saving it to SQLite, but I am looking to do the opposite. Any suggestions or references would be greatly appreciated. I have developed a Haskell ap ...

Tips for ensuring the border matches the size of the image

I am in the process of creating a website that includes a filter option. My plan is to have the filters displayed on the left side and the items on the right side. To achieve this layout, I have implemented a scrollable div for the items. However, I notic ...

What is the best way to convert a dictionary into a string using a custom style?

I have a challenge of converting a dictionary type to a string format like: name=tom&age=12%sex=m Initially, I tried the following approach: params=sorted([(k, v) for k, v in dic.items()]) src="" for param in params: src+=param[0]+"="+param[1]+"& ...

Retrieve the updated file name from the mini file upload form

I have implemented the Mini AJAX Upload Form from this tutorial to upload files to a server. I made modifications to add a timestamp at the end of the file name. How can I return the updated file name (with the timestamp) back to the client for future refe ...

Create dynamic and interactive content by embedding text within SVG shapes using the powerful D

How can I write text into an SVG shape created with d3.js and limit it to stay inside the shape similar to this example http://bl.ocks.org/mbostock/4063582? I attempted to use a clipPath following the example provided. However, when inspecting with firebu ...