PK-1825
PK-1825

Reputation: 1489

how to bind nested json data into angularjs dropdown?

I have some json data related to timzone below i need to bind particular nested value into dropdown, in using angularjs, in timezone array its coming as string format i need to bind those into dropdown.

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"
          ]
        },
    }
    }

Script--

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

HTML Content

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

Upvotes: 1

Views: 472

Answers (2)

Omar Makled
Omar Makled

Reputation: 1866

First off manipulate data and then populate 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);

});

Demo

Upvotes: 0

NTP
NTP

Reputation: 4448

You can use the following to iterate through your object keys and populate your 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>

Demo

Upvotes: 3

Related Questions