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

Populate dependent selects via Angular from json file

本文关键字:填充 依赖 选择 文件 Angular json 通过      更新时间:2023-09-26

我有一个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;
  });
});

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

您需要为国家内的地区添加属性,由于它是可变的,请使用[]符号:

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