如何使用具有字符串数组的JSON对象填充选择ng-options?

时间:2016-11-09 03:41:50

标签: angularjs arrays json sorting grouping

目前我有这个JSON对象:

 {
    "hospitalId" : "0002",
    "name" : "test form",
    "procedureId" : "0002-testform",
    "steps" : [ 
        {
            "title" : "Brand",
            "value" : [ 
                "jonson", 
                "smith", 
                "braun"
            ]
        }, 
        {
            "title" : "Procedure type",
            "value" : [ 
                "total", 
                "unicompartimental"
            ]
        }
    ]
}

我需要在多选中显示它,如下所示:

<strong>Brand</strong>
<ul>braun</ul>
<ul>jonson</ul>
<ul>smith</ul>

<strong>Procedure type</strong>
<ul>total</ul>
<ul>unicompartimental</ul>

它们需要按steps.title和steps.value排序,事情是:我无法弄清楚如何使用<select ng-options>标记正确显示它们,这就是我尝试过的:

<select multiple ng-model="step" ng-options="step[0].value  group by step.title for step in loadedSteps.steps " ></select>

给我:品牌未定义

<select multiple ng-model="step" ng-options="step.value  group by step.title for step in loadedSteps.steps | orderBy:['value']"></select>

给我:品牌 [jonson,smith,braun]

此外,我尝试使用嵌套<option>,但它没有订购......

非常感谢任何帮助,提前谢谢

1 个答案:

答案 0 :(得分:0)

以下是您正在寻找的答案。

您应该使用两个ng-repeat,首先用于显示title,其他用于在标题中显示values

第一个ng-repeat以标题开头,以该标题中的值结束。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = 
 {
 "hospitalId": "0002",
 "name": "test form",
 "procedureId": "0002-testform",
 "steps": [{
  "title": "Brand",
  "value": [
   "jonson",
   "smith",
   "braun"
  ]
 }, {
  "title": "Procedure type",
  "value": [
   "total",
   "unicompartimental"
  ]
 }]

}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
 <div >
      <label>{{step.title}}</label>
    <select>
    <option ng-repeat-start="step in names.steps | orderBy:'title'" ng-bind="step.title"></option>
    <option ng-repeat-end ng-repeat="opt in step.value | orderBy:'step.value':true" ng-bind="' - ' + opt"></option>
    </select>
    
  </div>
</div>


</body>
</html>

请运行此代码段

HEre is a plunker