从json文件中通过Angular填充依赖选择

时间:2015-09-28 23:06:17

标签: javascript json angularjs select ng-options

我有一个带有下一个结构的JSON文件

  {
  "regions": [
    "Africa",
    "The Americas",
    "Asia",
    "Europe",
    "Middle East"
  ],
  "countries": {
    "Africa": [
      "Algeria",
      "Egypt",
      "Morocco",
      "South Africa",
      "Tunisia",
      "Other African Countries"
    ],
    "Asia": [
      "China",
      "Japan",
      "Other Asian Countries"
    ],
    "Europe": [
      "Austria",
      "Baltic States - Lithuania, Latvia, Estonia",
      "Belgium",
      "Bulgaria",
      "Croatia",
      "Czech Republic",
      "Denmark",
      "Finland",
      "France",
      "Germany",
      "Greece",
      "Hungary",
      "Iceland",
      "Ireland",
      "Italy",
      "Luxemburg",
      "Netherlands",
      "Norway",
      "Poland",
      "Portugal",
      "Romania",
      "Russia",
      "Slovakia",
      "Slovenia",
      "Spain",
      "Sweden",
      "Switzerland",
      "Ukraine",
      "United Kingdom",
      "Other European Countries"
    ],
    "Middle East": [
      "Afghanistan",
      "Armenia",
      "Azerbaidjan",
      "Bahrain",
      "Georgia",
      "Iran",
      "Iraq",
      "Israel",
      "Jordan",
      "Kazakhstan",
      "Kuwait",
      "Kyrgyzstan",
      "Lebanon",
      "Mongolia",
      "Oman",
      "Qatar",
      "Saudi Arabia",
      "Tadzhikistan",
      "Turkey",
      "United Arab Emirates",
      "Uzbekistan",
      "Yemen",
      "Other Middle-East Countries"
    ]
  }

我需要创建两个依赖选择。首先 - 我选择地区,并根据地区 - 选择所选国家。

HTML

<html lang="en" ng-app="myapp">
<head>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>   
<div ng-controller="myCtrl">

    <select ng-model="selectedRegion" data-ng-options="location for location in selected.regions">
        <option value="">Region</option>
    </select>
    <select ng-model="selectedCountry" ng-options="place for place in selected.countries.selectedRegion">
        <option value="">Country</option>
    </select>

</div>

</body>
</html>

电脑板

angular.module('myApp').controller('myCtrl', function($http, $scope) {
  $http.get('contacts.json').success(function (data) {
     $scope.select = data;
  });
});

第二个选择不起作用。请帮忙。谢谢。这是plunker - http://plnkr.co/edit/1AZNUyiRJclF7cdFOLjA?p=preview

1 个答案:

答案 0 :(得分:0)

您需要在国家/地区内为区域添加属性,因为它是可变的,请使用[]表示法:

<select data-ng-options="place for place in selected.countries[selectedRegion]" ng-model="..">

DEMO