Angular JS ng-options 从 JSON 选择列表

Angular JS ng-options selecting list from JSON

我正在尝试使用 selectng-options 来填充我的下拉列表。这是我的 JSON

{ "Food": [ { "Name": Apple, "HealthCondition": [ { "Name": "High Blood Pressure", "Eat": null }, { "Name": "High Cholesterol", "Eat": null }, { "Name": "Heart Disease", "Eat": null }, { "Name": "Osteoporosis", "Eat": null }, { "Name": "Digestive Disorder", "Eat": null } ] }

这是我的 select <select class="chosen-select" ng-model="selectedValue" ng-options="x.HealthCondition for x in myResults.Food" multiple chosen></select> 我得到的结果是 [object Object],[object Object],[object Object],[object Object],[object Object]

我正在尝试获取健康状况名称列表!任何帮助将不胜感激。难倒这个几个小时。我正在使用 Angular Chosen 指令。如果我只使用 x.Name 之类的名称字段,但我想获取 HealthCondition 名称,这将正常工作。

如有任何帮助,我们将不胜感激!

尝试<select class="chosen-select" ng-model="selectedValue" ng-options="x.Name as x.Name for x in myResults.Food.HealthCondition" multiple chosen></select>

问题是您的数据无法以其当前格式用于 ng-options。您需要将可用的 HealthConditions 缩减为单个数组,而不是将 HealthCondition 数组作为 属性 的多个对象。

在您的控制器中,您需要将数据映射到单个数组,如下所示:

$scope.HealthConditions = myResults.reduce(function(arr, result){ 
    for(var i in result.HealthCondition){
        arr.push(result.HealthCondition[i]);
    }
    return arr;
}, []);

然后在您的视图中使用以下内容:

<select class="chosen-select" ng-model="selectedValue" ng-options="x.Name for x in HealthConditions" multiple chosen></select>

一些观察:

  • 您的 JSON 无效。 Apple 应该是针对 name 键的字符串。
  • 您正在迭代 ng-options 中的 Food 数组,它应该是 HealthCondition

演示版

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    $scope.jsonObj = {
  "Food": [
    {
      "Name": "Apple",
      "HealthCondition": [
        {
        "Name": "High Blood Pressure",
        "Eat": null
        },
        {
        "Name": "High Cholesterol",
        "Eat": null
        },
        {
        "Name": "Heart Disease",
        "Eat": null
        },
        {
        "Name": "Osteoporosis",
        "Eat": null
        },
        {
        "Name": "Digestive Disorder",
        "Eat": null
        }
    ]
}]};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <select class="chosen-select" ng-model="selectedValue" ng-options="x.Name as x.Name for x in jsonObj.Food[0].HealthCondition" multiple chosen></select>
</div>