Angular select填充下拉列表?

时间:2016-03-04 13:00:46

标签: angularjs json ng-options

这是我的JSON数据:

[{
  "table":"mCity",
  "drpdownItems":[
     {
        "Display":"ab",
        "Value":1
     },
     {
        "Display":"a",
        "Value":10
     },
     {
        "Display":"Delhi",
        "Value":7
     },
     {
        "Display":"Devgad",
        "Value":4
     },
     {
        "Display":"Kalyan",
        "Value":5
     },
     {
        "Display":"Mumbai",
        "Value":2
     },
     {
        "Display":"Nashik",
        "Value":9
     },
     {
        "Display":"New Mumbais",
        "Value":6
     },
     {
        "Display":"Panji ",
        "Value":8
     },
     {
        "Display":"Pune",
        "Value":3
     }
  ]
}]

我想要以下输出:

<select>
    <option value="1">ab</option>
    <option value="10">a</option>
    <option value="7">Delhi</option>
</select>

我试过以下:

ng-options="City.Display as City.Value for drpdownItems in CmbsData.table['mCity']"

2 个答案:

答案 0 :(得分:0)

ng-options="City.Display as City.Value for drpdownItems in CmbsData[0].drpdownItems"

Cmbs是一个数组,drpdownItems是对象的属性,它是该数组的第一个元素

根据评论进行编辑:广义形式     ng-options =“City.Display as City.Value for drpdownItems in(CmbsData | filter:{table:'mCity'})。drpdownItems”

答案 1 :(得分:0)

根据以下评论进行更新:

<select 
    ng-options="City.Value as City.Display for City in (CmbsData | filter:{table:'mCity'}:true|limitTo:1)[0].drpdownItems"
    ng-model="selectedCity">
</select>

为了进行严格匹配,请在true limitTo:1 filter. It is better to use过滤器because there may be multiple matches. limitTo and [0]`索引中使用always result in an array. Since we are limiting by 1, we can use获得我们想要的城市。

原始回答:

你需要像这样使用

<select name="" id="" ng-options="City.Value as City.Display for City in CmbsData[0].drpdownItems" ng-model="selectedCity"></select>

ng-options的语法是_select_ (as _label_)? for (_key_,)?_value_ in _collection_