Angular JS ng-options从JSON中选择列表

时间:2017-02-12 20:46:22

标签: angularjs json ng-options angular-chosen

我尝试使用select ng-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 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名称,这是正常的。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

问题是您的数据无法用于当前格式的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>

答案 2 :(得分:0)

一些观察结果:

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

<强>样本

&#13;
&#13;
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
        }
    ]
}]};
});
&#13;
<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>
&#13;
&#13;
&#13;