Search code examples
arraysangularjsjsonmaterialize

How do I populate a multiple select dropdown with JSON data using Materialize and Angularjs?


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>

Solution

  • 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