如何在带有对象的数组中使用ng-options

时间:2017-06-19 09:39:14

标签: angularjs

我有一个如下所示的数据源:

var categories = 
[{
{"name":"First Category","subcats":[
{"name":"Sub Category 1"},
{"name":"Sub Category 2"},
{"name":"Sub Category 3"}]
},{
{"name":"Second Category","subcats":[
{"name":"Sub Category 1"},
{"name":"Sub Category 2"},
{"name":"Sub Category 3"}]
}]

我无法弄清楚如何使用ng-options显示按主类别分组的子类别。结果应如下所示:

<select>
   <optgroup>First Category
      <option>Sub Category 1</option>
      <option>Sub Category 2</option>
      <option>Sub Category 3</option>
   </optgroup>
   <optgroup>Second Category
      <option>Sub Category 1</option>
      <option>Sub Category 2</option>
      <option>Sub Category 3</option>
   </optgroup>
</select>

2 个答案:

答案 0 :(得分:1)

1)修复您的categories数组;

2)将其展平以与ngOptionsgroup by一起使用。

示例:

&#13;
&#13;
angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
    var categories  = 
    [
        {
            "name": "First Category",
            "subcats": [
                {"name": "Sub Category 1"},
                {"name": "Sub Category 2"},
                {"name": "Sub Category 3"}
            ]
        },
        {
            "name": "Second Category",
            "subcats": [
                {"name": "Sub Category 1"},
                {"name": "Sub Category 2"},
                {"name": "Sub Category 3"},
              	{"name": "Sub Category 4"}
            ]
        }
    ];
    
    $scope.options = [];
    
    angular.forEach(categories, function (category){
    	angular.forEach(category.subcats, function (subCat){
      	subCat.categoryName = category.name;
      	$scope.options.push(subCat);
      });
    });
  
});
&#13;
<script src="https://code.angularjs.org/1.6.2/angular.js" ></script>
<html ng-app="plunker">
  <body ng-controller="MainCtrl">
  
     <select ng-model="test.model" 
        ng-options="option.name group by option.categoryName for option in options">
    </select>
    
  </body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

this.categories =
  [
    {
      "name": "First Category",
      "subcats": [
        { "name": "Sub Category 1" },
        { "name": "Sub Category 2" },
        { "name": "Sub Category 3" }]
    },
    {
      "name": "Second Category",
      "subcats": [
        { "name": "Sub Category 4" },
        { "name": "Sub Category 5" },
        { "name": "Sub Category 6" }]
    }
  ];

并在模板中:

<select>
  <optgroup *ngFor="let category of categories;" label="{{category.name}}">
    <option *ngFor="let sub of category.subcats;">{{sub.name}}</option>
  </optgroup>