Reputation: 137
I'm quite new with Angular,and I'm facing some problems when trying to bind values of a Json file into a select form.I've read lot of solutions and I used all of them but I don't know why it does not display me anything.I take the Json file with an $http.get,I put this file into a variable and I try to access one element and all is ok,so the file is taken in the rigth way. The Json is this one:
{
"regioni": [
{
"province": [
{
"code": "CH",
"comuni": [
{
"code": "069001",
"cap": "66040",
"nome": "Altino"
},
{
"code": "069002",
"cap": "66044",
"nome": "Archi"
}
],
"nome": "Chieti"
}
],
"nome": "Abruzzo"
}
]
}
So I have an array of region containing a property nome and a property province which is an array containing code,nome,and an array of comuni composed by code,cap,nome. I want to display every name of all comuni of all province. The controller is this one:
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 HTML :
<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 don't know exactly how to take that value but I hoped this worked. Thanks in advance.
Upvotes: 0
Views: 661
Reputation: 451
First of all, in the $http response, it's regioni which receives the data like this:
$http.get('/resources/italia_comuni.json')
.then(function(response){
$scope.regioni = response.data;
});
then you should write ng-options like this:
ng-options="c.nome for c in regioni[0].province[0].comuni"
check this link http://plnkr.co/edit/cSY0GY6E7zRCbZm14Zps?p=preview
Upvotes: 1
Reputation: 178
Yes, it's like younes sofiane said: to actually take advantage of the response you should use the $scope.regioni instead of a regular javascript variable.
Take a look at this example:
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
Now the html:
<div ng-controller="GreetingController">
{{ greeting }}
</div>
To understand this better, take a look at the angular developer guide on the basics: https://docs.angularjs.org/guide/controller
Upvotes: 1