Reputation: 162
I've seen numerous examples of angularjs using JSON data to populate options in a select dropdown, but after numerous attempts and variations I still end up with a blank dropdown menu. I'm sure there's something wrong with my object naming convention, as all the angular examples are pretty confusing (what's plural? what isn't? etc.) Any help you can offer would be greatly appreciated.
JSON example:
{"fields":[
{"state": "OH",
"gender": "male"},
{"state": "OH",
"gender": "female"},
{"state": "IN",
"gender": "male"}
]};
html:
<div class="input-field col s12 m4" ng-app="totalQuery" ng-controller="queryCtrl">
<select multiple>
<option ng-repeat="fields in myData">{{fields.state}}</option>
</select>
<label>First Category</label>
</div>
<div class="input-field col s12 m4" ng-app="totalQuery" ng-controller="queryCtrl">
<select multiple>
<option ng-repeat="fields in myData">{{fields.gender}}</option>
</select>
<label>Second Category</label>
</div>
angularjs:
<script>
var app = angular.module('totalQuery', []);
app.controller('queryCtrl', function($scope, $http){
$http.get("file.json").then(function(response){
$scope.myData = response.data.fields;
});
});
</script>
Upvotes: 0
Views: 2457
Reputation: 878
First of all you don't need to define ng-app
and ng-controller
twice.
Secondly what I don't understand is why are you using two drop down menu's or jump menu to change the state and according to that you will bring the gender ? right ?
If that's the case usually when you you are working with drop down menu you need an id for each option which will be sent back to bring changed item on the basis of id.
I've made a working plunker Populate Drop Down with Json please take a look if that's what you need. I'm sure you will get the idea how to do it.
Upvotes: 0
Reputation: 282
You just need to add .fields into your ng-repeat.
Change:
<option ng-repeat="fields in myData">{{fields.state}}</option>
To:
<option ng-repeat="fields in myData.fields">{{fields.state}}</option>
Here is a jsFiddle of the solution: http://jsfiddle.net/eLnfgnc9/4/
It is worth noting, that it is better to use ng-options instead of ng-repeat. I find it more confusing than ng-repeat but it just seems to work better. Here is a link to the angular doc for ng-options: https://docs.angularjs.org/api/ng/directive/ngOptions
Upvotes: 1