如何使用ng-options显示父级和子级

时间:2016-03-25 23:04:48

标签: angularjs json ng-options

我想创建ng-options,我可以从父对象和子对象中选择元素。 我的json看起来像这样:

{
"errors":[

],
"headquarters":{
  "id":1,
  "name":"headquarter name",
  "departments":[
     {
        "id":2,
        "name":"department A name",
        "divisions":[
           {
              "id":6,
              "name":"Division A name"
           },
           {
              "id":7,
              "name":"Division B name"
           },
           {
              "id":8,
              "name":"Division C name"
           }
        ]
     },
     {
        "id":3,
        "name":"department B name",
        "divisions":[
           {
              "id":11,
              "name":"Division E name"
           },
           {
              "id":12,
              "name":"Division F name"
           },
           {
              "id":13,
              "name":"Division G name"
           }
        ]
     }
  ]
 }
 }

从这个Json我想选择总部或部门然后如果选择部门而不是总部,则使用选择的id来选择部门。我试着做这样的事情:

      element.id as element.name for element in user.structure.headquarters && user.structure.headquarters.departments

但它没有用。

这可能吗?

或者还有其他办法吗?

JSON中总是只有一个总部。

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情先选择部门,然后从选定的部门获得部门

http://plnkr.co/edit/PTWxUHobi7agUlB9fCHv?p=preview

您的HTML看起来像这样:

<select ng-model="selectedDept" 
        ng-options="dept.id as dept.name for dept in data.headquarters.departments"
        ng-change="getDivisions()"></select>


<select ng-if="selectedDept" 
        ng-model="selectedDivision" 
        ng-options="div.id as div.name for div in selectedDivisions"></select>