e如何使用ng-options创建下拉(分组)?

时间:2016-12-02 05:44:56

标签: angularjs ng-options angularjs-ng-options

我和我一起拥有所有国家的json。

{"countries":[
{"name":"Afghanistan","code":"AF"},
{"name":"Åland Islands","code":"AX"},
{"name":"United States","code":"US"},
{"name":"Canada","code":"CA"},
{"name":"India","code":"IN"}
]};

我想创建下拉列表

"
Choose Country(Default)
United States
Canada
------------
Åland Islands
Afghanistan
India
So on..."

我可以通过ng-repeat来实现

<select name="country" id="country" data-ng-model="country" required data-ng-change="allSelect()">
    <option value="default" data-ng-data-ng-bind="'Choose Country'"></option>
    <option value="{{cList.code}}" data-ng-if="cList.code === 'US'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
    <option value="{{cList.code}}" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
    <option value="default1">--------------------------------------------------</option>
    <option value="{{cList.code}}" data-ng-if="cList.code !== 'US' && cList.code !== 'CA'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
</select>

我如何通过ng-options做到这一点?

目前,如果我想在默认情况下选择任何选项,则不会发生其创建空白字符串。 我从不同的ajax调用获得的国家列表和默认值。

1 个答案:

答案 0 :(得分:2)

您需要对JSON进行一些更改

<强> JSON

android-debug.apk

<强> HTML

{
  "Collections": [{
    "Name": "North America",
    "Countries": [{
        "Name": "United States",
        "code": "US"
      }, {
        "Name": "Canada",
        "code": "CA"
      }

    ]
  }, {
    "Name": "Asia",
    "Countries": [{
        "Name": "India",
        "value": "IN"
      }

    ]
  }]

}

<强>控制器

<body ng-controller="dobController">
  <div class="col-md-20">
    <div id="main">
      <form class="form-horizontal" role="form">
        <label class="control-label col-md-2">Filter List:</label>
        <div class="col-md-5">
          <select ng-model='theModel' ng-change="display(theModel)">
            <optgroup ng-repeat='group in collection' label="{{group.Name}}">
              <option ng-repeat='veh in group.Countries' value='{{group.Name}}::{{veh.Name}}'>{{veh.Name}}</option>
            </optgroup>
          </select>
        </div>
      </form>
    </div>
  </div>

<强> DEMO