繁体   English   中英

如何将嵌套的json数据绑定到angularjs下拉列表中?

[英]how to bind nested json data into angularjs dropdown?

我有一些与timzone相关的json数据,我需要将特定的嵌套值绑定到下拉列表中,在使用angularjs时,在时区数组中它以字符串格式出现我需要将它们绑定到下拉列表中。

timezone.json -

 {
      "countries": {
     "US": {
          "id": "US",
          "name": "United States",
          "timezones": [
            "America/New_York",
            "America/Detroit",
             ]
        },
     "CA": {
          "id": "CA",
          "name": "Canada",
          "timezones": [
            "America/St_Johns",
            "America/Halifax",
           ]
        },
    "IN": {
          "id": "IN",
          "name": "India",
          "timezones": [
            "Asia/Kolkata"
          ]
        },
    }
    }

脚本 -

$http({
    method: "GET",
    url: 'timezon.json'
}).then(function mySuccess(response) {
    $scope.timeZones = response.data;
}, function myError(response) {
    $scope.timeZones = response.statusText;
});

HTML内容

 <select class="form-control">
        <option value="0">--Select Time Zones></option>
  </select>

您可以使用以下内容迭代对象键并填充您的选择。

<select class="form-control">
    <option value="0">--Select Time Zones></option>
    <option ng-repeat="(key, value) in data.countries" value="value.id">{{value.timezones.toString()}}</option>
</select>

演示

首先操纵数据,然后填充选择

HTML

<div ng-app="app" ng-controller="Ctrl" ng-init="getTimeZones">
  <h1>{{selectedTimezone}}</h1>
<select ng-model="selectedTimezone" ng-options="item for item in timezones">
</select>
</div>

JS

var app = angular.module("app", []);

app.controller('Ctrl', function($scope, $filter) {
  $scope.timezones = []
  $scope.data = {
    "countries": {
     "US": {
          "id": "US",
          "name": "United States",
          "timezones": [
            "America/New_York",
            "America/Detroit",
             ]
        },
     "CA": {
          "id": "CA",
          "name": "Canada",
          "timezones": [
            "America/St_Johns",
            "America/Halifax",
           ]
        },
    "IN": {
          "id": "IN",
          "name": "India",
          "timezones": [
            "Asia/Kolkata"
          ]
        },
    }
  }

  $scope.getTimeZones = setTimeout(function(){ 
    // http request here after success
    for (var key in $scope.data.countries) {
      var timezones = $scope.data.countries[key].timezones;
      timezones.unshift($scope.data.countries[key].name);
      Array.prototype.push.apply($scope.timezones, timezones);
      // For ES6
      // $scope.timezones.push(...timezones)
    }

  }, 1000);

});

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM