Mpondomise Mpondomise - 1 month ago 31
Javascript Question

angularjs ng-repeat drop down menu from json nested

I have the following example.json file:

[
{
"interests": [
{
"item": "art"
},
{
"item": "literature"
},
{
"item": "history"
},
{
"item": "science"
}
]
},
{
"experience": [
{
"year": "novice"
},
{
"year": "experienced"
}
]
}
]


and in my view controller, I read the file like this:

app.controller('ProfileCtrl', ["$scope", "$state", "$http",
function ($scope, $state, $http) {

$http.get('files/example.json').success(function (data)
{
$scope.myjsonobj= data;
});


and in my html view, I am injecting the values like this:

<div ng-controller="ProfileCtrl">
...
<select class="form-control" ng-model="user.favs">
<option ng-repeat="p in interests.myjsonobj" value="{{p.item}}">{{p.item}}</option>
</select>


question:



How can I show only the list of values of "interests" in my dropdown menu? How can I access the nested json array in angularjs?

my current setup is not working.

Answer

assuming 'interests' is your controller shortname.

you can use:

<option ng-repeat="p in myjsonobj[0].interests" value="{{p.item}}">{{p.item}}</option>

Ideally, you should loop the data object to find the index with the 'interests' key vs hardcoding [0].

update: removed "interests." from the repeat. doesn't seem like you have the ctrl shortname binding.

Comments