如何在角度js中使用Array对象json创建选择框?

时间:2017-04-22 08:45:24

标签: angularjs

我正在尝试从json对象显示国家/地区名称。 json数据查找数组对象的集合,这个对象使用ng-repeat迭代json数据并显示到选择框中。我试过下面的代码。

Json
----

$scope.countries = [
  {
    "AT": "Austria"
  },
  {
    "CI": "Côte d'Ivoire"
  },
  {
    "CG": "Congo"
  },
  {
    "SV": "El Salvador"
  },
  {
    "IN": "India"
  },
  {
    "SX": "Sint Maarten (Dutch part)"
  },
  {
    "SZ": "Swaziland"
  },
  {
    "CH": "Switzerland"
  },
  {
    "AE": "United Arab Emirates"
  }
]

html
----
<select ng-model="counryNames" >
          <option ng-repeat="(key,country) in countries"  value="{{key}}">{{country[key]}}</option>
     </select>

1 个答案:

答案 0 :(得分:1)

更改您的ng-repeat,您应该访问 countries 而不是country

的键
<option ng-repeat="(key, value) in countries" value="{{key}}">{{countries[key]}}</option>

<强>样本

&#13;
&#13;
   angular.module("myapp", [])
      .controller("MyController", function($scope) {
         $scope.countries = [{
            "AT": "Austria"
          }, {
            "CI": "Côte d'Ivoire"
          }, {
            "CG": "Congo"
          }, {
            "SV": "El Salvador"
          }, {
            "IN": "India"
          }, {
            "SX": "Sint Maarten (Dutch part)"
          }, {
            "SZ": "Swaziland"
          }, {
            "CH": "Switzerland"
          }, {
            "AE": "United Arab Emirates"
          }]; 
      });
&#13;
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>  
</head>
<body ng-app="myapp">
  <div ng-controller="MyController">
     <select>
    <option ng-repeat="(key, value) in countries" value="{{key}}">{{countries[key]}}</option>
</select>
  </div>
</body>
&#13;
&#13;
&#13;