如何使用 Materialize 和 Angularjs 使用 JSON 数据填充多个 select 下拉列表?

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

我见过许多 angularjs 使用 JSON 数据填充 select 下拉列表中的选项的示例,但经过多次尝试和变化后,我仍然得到一个空白下拉式菜单。我确定我的对象命名约定有问题,因为所有 angular 示例都非常令人困惑(什么是复数?什么不是?等等)。将不胜感激您能提供的任何帮助。

JSON 例子:

{"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>

您只需将 .fields 添加到您的 ng-repeat 中。
变化:

<option ng-repeat="fields in myData">{{fields.state}}</option>

收件人:

<option ng-repeat="fields in myData.fields">{{fields.state}}</option>

这是解决方案的 jsFiddle:http://jsfiddle.net/eLnfgnc9/4/

值得注意的是,最好使用 ng-options 而不是 ng-repeat。我发现它比 ng-repeat 更令人困惑,但它似乎工作得更好。这是 ng-options angular 文档的 link:https://docs.angularjs.org/api/ng/directive/ngOptions

首先你不需要定义ng-appng-controller两次。

其次,我不明白的是你为什么要使用两个下拉菜单或跳转菜单来改变状态,并据此带来性别?对吗?

如果通常是这种情况,当您使用下拉菜单时,您需要为每个选项分配一个 ID,该 ID 将被发回以根据 ID 带来更改的项目。

我制作了一个可以使用的 plunker Populate Drop Down with Json 请看一下是否是您需要的。我相信您会知道如何去做。