Reputation: 737
I have been working with json files and angularjs,since i made changes to the json file to make it more complete with information, the structure of the file became more complex, now i can't access the data they way i used to. It's supposed to be the same way but it's not loading.
this is the jason: http://www.jsoneditoronline.org/?id=72e10a49f6f7650a864dda13a3f2d56a, (Note: estado=state, localidad=location i'm trying to display the locations from various states in a chosen select).
How i load json data into the html:
<select class="control-group chosen-select" chosen id='sl_edo' style="width:300px;">
<!-- also i tried ng-repeat="pueblo in pueblos" which worked with the old json file-->
<optgroup ng-repeat="pueblo in pueblos[0] | orderBy:'estado'" label={{pueblo.estado}}>
<option>{{pueblo.localidad}}</option>
</optgroup>
</select>
some tests i did to check how is the data structure
<p>{{pueblos[0].estado}}</p>
This line brings me this
[{"Jalisco":{"localidad":{"Tequila":,etc...
another html line i tested
<p>{{pueblos[0]}}</p>
{"estado":[{"Jalisco":{"localidad":{"Tequila"
Upvotes: 0
Views: 54
Reputation: 68
Your data structures are a little off. You want similar objects to have the same structure. For instance, right now, to access the "Jalisco" object, you have to call pueblos[0].estado[0].Jalisco
or pueblos[0].estado[0]["Jalisco"]
. But if you try pueblos[0].estado[1].Jalisco
, you get an error, because estado[1]
only has "Sonora" as an attribute. Instead, you probably want a structure like this:
estados = [
{
"nombre": "Jalisco",
"localidades": [
{
"nombre": "Tequila",
"oferta": {
"gen": 99,
"ecas": 66,
},
},
],
}
]
In this structure, you can access the name of the state by estado[#idx].nombre
. Then if you want that state's localitities, it's estado[#idx].localidades[#idx]
. So if you want the "gen" attribute of the "oferta" in Tequila, you access it like this, estados[0].localidades[0].oferta.gen
. Basically, if you're working with a list that you loop over using ng-repeat, all the objects should share the same attribute names. You should never use distinct names as attribute names, like using "Jalisco" or "Sonora" as attributes.
Upvotes: 2