这个 select 的 angular ng-option 是什么?

What would be angular ng-option equivalent of this select?

我正在努力将它变成 ng-option。有可能吗?

<select ng-model="detail_type_id">
   <optgroup ng-repeat="type in data.detailTypes" label="{{type.name}}">
      <option ng-repeat="t in type.children" value="{{t.id}}">{{t.name}}</option>
   </optgroup>
</select>

DetailTypes 看起来像这样:

[
 {"id":7, 
  "parent_id":null, 
  "name":"Contact", 
  "children":[
     {"id":8,
      "parent_id":7,
      "name":"Address",
      "children":[]
     },
     {"id":12,
      "parent_id":7,
      "name":"Something else",
      "children":[]
     }
   ]},
 {"id":16,
  "parent_id":null,
  "name":"Other",
  "children":[
     {"id":10,
      "parent_id":16,
      "name":"Remarks",
      "children":[]}
   ]
 }
]

Child需要选择id。嵌套不能更深。

ngOptions 指令不适用于多维对象。所以你需要展平你的阵列才能使用它。

我为此写了一个过滤器:

app.filter('flatten' , function(){
  return function(array){
    return array.reduce(function(flatten, group){
      group.children.forEach(function(child){
        child.groupName = group.name;
        flatten.push(child)
      })
      return flatten;
    },[]);
  }
})

而 HTML 部分将是这样的:

<select ng-model="detail_type_id"
        ng-options="item.id as item.name 
                    group by item.groupName for item 
                    in data.detailTypes | flatten track by item.id">
</select>

Plunker(带过滤器的版本 #1): https://plnkr.co/edit/dxi7j8oxInv2VRJ1aL7F

我也把你的对象修改成这样:

[{
  "id": 7,
  "parent_id": null,
  "name": "Contact",
  "children": [{
    "id": 8,
    "parent_id": 7,
    "name": "Address",
    "children": []
  }, {
    "id": 12,
    "parent_id": 7,
    "name": "Something else",
    "children": []
  }]
}, {
  "id": 16,
  "parent_id": null,
  "name": "Other",
  "children": [{
    "id": 10,
    "parent_id": 16,
    "name": "Remarks",
    "children": []
  }]
}]

编辑:

根据建议我写了另一个没有过滤器的版本,但在控制器内展平了数组。

附加控制器JS:

$scope.flattenDetailTypes = flattenDetailTypes($scope.data.detailTypes);

  function flattenDetailTypes(array){
    return array.reduce(function(flatten, group){
      group.children.forEach(function(child){
        child.groupName = group.name;
        flatten.push(child)
      })
      return flatten;
    },[]);
  }

标记:

<select ng-model="detail_type_id"
        ng-options="item.id as item.name group by item.groupName for item in flattenDetailTypes track by item.id"></select>

Plunker(版本 #2 没有过滤器): https://plnkr.co/edit/D4APZ6