how to bind nested json data into angularjs dropdown? - javascript

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>

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

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

Related

Populate selectors using json doesn't work as expected

I am trying to make two selector's populated with JSON. One for states and one for cities. If i choose a state the next selector is supposed to show me the cities that are in that state.
I've made it so far using functions. My state function is working fine, but I'm having troubles with my city selector. It doesn't show anything.
I'm stuck here.
In my scripts.js I have
function populateState(data){
var listState = "";
for(var i in data.states){
listState += '<option value="'+data.states[i].id+'">'+data.states[i].name+'</option>';
}
$('#states').html(listState);
}
function populateCities(data){
var listobj = "";
for(var i in data.states.cities){
listobj += '<option value="'+data.states.cities[i].id+'">'+data.states.cities[i].name+'</option>';
}
$('#cities').html(listobj);
}
And in my ready.js where i use the functions I have
var dataJson = {
"states": [
{
"name": "First state",
"id": "1",
"cities": [
{
"name": "city1",
"id": "cos"
},
{
"name": "city2",
"id": "mio"
},
{
"name": "city3",
"id": "top"
}
]
},
{
"name": "Second state",
"id": "2",
"cities": [
{
"name": "city4",
"id": "or"
},
{
"name": "city5",
"id": "st"
},
{
"name": "city6",
"id": "bs"
}
]
},
]
};
$(document).ready(function() {
populateState(dataJson);
$("#states").change(function () {
populateCities(dataJson);
});
});
Here`s the HTML
<select id="states" >
<option value="000">-Select State-</option>
</select>
<select id="cities" >
<option value="000">-Select Cities-</option>
</select>
The issue is that you can't iterate through the cities like that, with for(var i in data.states.cities){...}. You need to iterate through just the cities belonging to the selected state.
Here's a working example.
function populateState(data){
var listState = "";
for(var i in data.states){
listState += '<option value="'+data.states[i].id+'">'+data.states[i].name+'</option>';
}
$('#states').html(listState);
}
function populateCities(data){
var listobj = "";
for(var i in data.states){
if (data.states[i].id == $("#states").val()) {
//this is the selected state, let's get their cities
for(var j in data.states[i].cities){
listobj += '<option value="'+data.states[i].cities[j].id+'">'+data.states[i].cities[j].name+'</option>';
}
}
}
$('#cities').html(listobj);
}
var dataJson = {
"states": [
{
"name": "First state",
"id": "1",
"cities": [
{
"name": "city1",
"id": "cos"
},
{
"name": "city2",
"id": "mio"
},
{
"name": "city3",
"id": "top"
}
]
},
{
"name": "Second state",
"id": "2",
"cities": [
{
"name": "city4",
"id": "or"
},
{
"name": "city5",
"id": "st"
},
{
"name": "city6",
"id": "bs"
}
]
},
]
};
$(document).ready(function() {
populateState(dataJson);
$("#states").change(function () {
populateCities(dataJson);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="states" >
<option value="000">-Select State-</option>
</select>
<select id="cities" >
<option value="000">-Select Cities-</option>
</select>
You would probably want to do something like call the populateCities as a callback when you're done with populateState on document.ready, since it comes up with the First state already selected, but doesn't populate its cities. But at least this will get you past your issue.

how to assign values from Json file to Javascript array

to populate the countries list in my typeahead search I am declaring manually.
var data = [
{
"id": "Austria",
"continent": "Europe"
},
...
{
"id": "USA",
"continent": "America"
}
];
I want the array data will get data from an external json file. Let's say my countries.json file contains this data
[
{
"id": "Austria",
"continent": "Europe"
},
{
"id": "France",
"continent": "Europe"
},
{
"id": "Japan",
"continent": "Asia"
},
{
"id": "USA",
"continent": "America"
}
]
I used getJSON To load the json data in my array data
var data = [];
$.getJSON( "js/countries.json", function(json){
data = json;
console.log(data);
});
The console shows me that data contains the values I need but in the rest of my code where I am using data as source it's not working. When I load data from Json file, i don't have any country shown in the search input.
Any suggestions please what I am missing ? Thank you.
var data = [{
"id": "Austria",
"continent": "Europe"
}, {
"id": "France",
"continent": "Europe"
}, {
"id": "Japan",
"continent": "Asia"
}, {
"id": "USA",
"continent": "America"
}];
typeof $.typeahead === 'function' && $.typeahead({
input: ".js-typeahead-input",
minLength: 0,
hint: true,
searchOnFocus: true,
group: {
key: "continent",
template: function(item) {
var continent = item.continent;
return continent;
}
},
emptyTemplate: 'no result for {{query}}',
groupOrder: ["Europe", "Asia", "America"],
display: ["id"],
correlativeTemplate: true,
dropdownFilter: [{
key: 'continent',
template: '<strong>{{continent}}</strong> continent',
all: 'All Countries'
}],
multiselect: {
matchOn: ["id"],
data: function() {
var deferred = $.Deferred();
return deferred;
}
},
template: '<span>' +
'<span class="id">{{id}}</span>' +
'</span>',
source: {
groupName: {
data: data
}
},
debug: true
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.js"></script>
<div class="typeahead__container">
<div class="typeahead__field">
<span class="typeahead__query">
<input class="js-typeahead-input"
name="q"
type="search"
autofocus
autocomplete="on">
</span>
</div>
</div>
Try
data = JSON.parse(json);
The request will get text and you need to parse that text into a JavaScript object. See how if I convert the object in your snippet to a string it needs to be parsed. Try
console.log(typeof json)
and you will see it is a string, not an array.
var data = JSON.parse(`[{
"id": "Austria",
"continent": "Europe"
}, {
"id": "France",
"continent": "Europe"
}, {
"id": "Japan",
"continent": "Asia"
}, {
"id": "USA",
"continent": "America"
}]`);
typeof $.typeahead === 'function' && $.typeahead({
input: ".js-typeahead-input",
minLength: 0,
hint: true,
searchOnFocus: true,
group: {
key: "continent",
template: function(item) {
var continent = item.continent;
return continent;
}
},
emptyTemplate: 'no result for {{query}}',
groupOrder: ["Europe", "Asia", "America"],
display: ["id"],
correlativeTemplate: true,
dropdownFilter: [{
key: 'continent',
template: '<strong>{{continent}}</strong> continent',
all: 'All Countries'
}],
multiselect: {
matchOn: ["id"],
data: function() {
var deferred = $.Deferred();
return deferred;
}
},
template: '<span>' +
'<span class="id">{{id}}</span>' +
'</span>',
source: {
groupName: {
data: data
}
},
debug: true
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.js"></script>
<div class="typeahead__container">
<div class="typeahead__field">
<span class="typeahead__query">
<input class="js-typeahead-input"
name="q"
type="search"
autofocus
autocomplete="on">
</span>
</div>
</div>

Binding json arrays in angular js select option

I am working with select box in angular js. i need to bind the data to the select box from the json,How do i populate json with arrays inside a select box in angular. i have the following code.
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x.names.name for x in names">
</select>
</div>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = {
"jobs": [
{
"Software": [
{
"name": "Developer",
"displayName": "App Developer"
},
{
"name": "Designer",
"displayName": "App Designer"
}
]
},
{
"Business": [
{
"name": "Sales",
"displayName": "Sales Manager"
},
{
"name": "Marketing",
"displayName": "Head of Marketing"
}
]
}
]
};
});
How do i populate the json $scope.names inside the select box. i am finding difficulty as the json have arrays. Thanks in advance
Try this one may be it will help you
Use ng-repeat on <select> tag
<select name="singleSelect" id="singleSelect" ng-model="selectedName">
<option value="">---Please select---</option> <!-- not selected / blank option -->
<option ng-repeat="n in names.software" value="{{n.name}}">{{n.displayName}}</option>
</select>
same way you can add different data.
It will be alot more easier if you prepare the data in your controller
$scope.values = [];
angular.forEach($scope.names, function (value, key) {
angular.forEach(value, function (value2, key2) {
angular.forEach(value2, function (value3, key3) {
angular.forEach(value3, function (value4, key4) {
$scope.values.push(value4.name);
});
});
});
});
and use $scope.values in your select
One possible way to do this by using custom directive.
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model='selectedName' custom-options>
<option value="">-- choose an option --</option>
</select>
</div>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = {
"jobs": [
{
"Software": [
{
"name": "Developer",
"displayName": "App Developer"
},
{
"name": "Designer",
"displayName": "App Designer"
}
]
},
{
"Business": [
{
"name": "Sales",
"displayName": "Sales Manager"
},
{
"name": "Marketing",
"displayName": "Head of Marketing"
},
{
"name": "Sales1",
"displayName": "Sales Manager1"
},
{
"name": "Marketing1",
"displayName": "Head of Marketing1"
}
]
}
]
};
}).directive("customOptions", function () {
return function (scope, element, attrs) {
var data = scope['names']['jobs'];
var propertyName = 'name';
if (angular.isArray(data)) {
angular.forEach(data, function(value, key) {
angular.forEach(value, function(ivalue, ikey) {
for (var i = 0; i < ivalue.length; i++) {
element.append(angular.element('<option>').text(ivalue[i][propertyName]).attr('value',ivalue[i][propertyName]));
}
})
});
}
}
})
JS FIDDLE

Access json data from angularjs

Here is my JSON file:
{
"countries":[
{
"country": "India",
"cities" : [{
"name": "Bangalore",
"rank": "40"
},
{ "name": "Mumbai",
"rank": "32"
},
{ "name": "Kolkata",
"rank": "54"
},
{ "name": "Chennai",
"rank": "42"
}]
},
{ "country": "China",
"cities":[{"name": "Guangzhou",
"rank": "111"
},
{ "name": "Fuzhou",
"rank": "21"
},
{ "name": "Beijing",
"rank": "90"
},
{ "name": "Baotou",
"rank": "23"
}]
}
]}
This is the angularjs code:
$scope.countryType = [
{ type: 'India', data:$scope.India, displayName:'India' },
{ type: 'China', data:$scope.China, displayName:'China'},
{ type: 'Ethiopia', data:$scope.Ethiopia, displayName:'Ethiopia'},
{ type: 'Cuba', data:$scope.Cuba, displayName:'Cuba'}
];
This angularjs code is fine for me but I don't know how to access name and rank from this data of countryType and I also want to filter it according to country.
For HTML page I am using this code :
<select ng-model="country.city" ng-options="country as country.type for country in countryType | orderBy: 'type'">
<option value=""> - Select a Country - </option>
</select>
<ul ng-repeat = "city in countryType | filter : country.city.data.cities.country ">
<li ng-repeat="details in city.data.cities">
<span> {{details.name}} </span>
<span> {{details.rank}}</span>
</li>
</ul>
Shall I have to use different code in html for accessing the data?
All the data is coming but I am not able to filter it.
So, basically you have two level of Arrays in your data structure. And that is why you need to do loop inside the country loop to access the cities.
A bit of change in your data structure, And here in an example for your reference:
HTML:
<div class="container">
<div ng-controller="FormController as formCtrl">
<table>
<tbody ng-repeat="country in formCtrl.contryType">
<tr>
<th colspan="2">{{country.country}}</th>
</tr>
<tr ng-repeat="city in country.cities">
<td>{{city.name}}</td>
<td>{{city.rank}}</td>
</tr>
</tbody>
</table>
</div>
</div>
JavaScript:
var app = angular.module("myApp", []);
app.controller("FormController", function () {
var ctrl = this;
ctrl.contryType = [{
"country" : "India",
"cities" : [{
"name" : "Bangalore",
"rank" : "40"
}, {
"name" : "Mumbai",
"rank" : "32"
}, {
"name" : "Kolkata",
"rank" : "54"
}, {
"name" : "Chennai",
"rank" : "42"
}
]
}, {
"country" : "China",
"cities" : [{
"name" : "Guangzhou",
"rank" : "111"
}, {
"name" : "Fuzhou",
"rank" : "21"
}, {
"name" : "Beijing",
"rank" : "90"
}, {
"name" : "Baotou",
"rank" : "23"
}
]
}
];
});
angular.bootstrap(document, ['myApp']);
Working Fiddle: http://jsfiddle.net/ashishanexpert/zvcx5z38/5/
You can not access object property by value as in $scope.India. You should be using a function to retrieve the cities of the given country.
$scope.getCityList = function(country)
{
var index = arrayObjectIndexOf($scope.countries, country, ["country"]);
return $scope.countries[index].cities;
}
function arrayObjectIndexOf(myArray, searchTerm, property) {
for(var i = 0, len = myArray.length; i < len; i++) {
var value = myArray[i];
for(var j=0; j<property.length; j++)
{
value = value[property[j]];
}
if (value === searchTerm) return i;
}
return -1;
}
So finally, the Angular JS code gets :
$scope.countryType = [
{ type: 'India', data:$scope.getCityList("India"), displayName:'India' },
{ type: 'China', data:$scope.getCityList("China"), displayName:'China'},
{ type: 'Ethiopia', data:$scope.getCityList("Ethiopia"), displayName:'Ethiopia'},
{ type: 'Cuba', data:$scope.getCityList("Cuba"), displayName:'Cuba'}
];
You can loop through the list JSON and store it in an array:
$scope.countryType = [];
angular.forEach(json.countries, function(data){
$scope.countryType.push({type: data.country, data: data});
});
Demo
Well you are accessing your data in a wrong way! Without changing your JS code you can use the following code, which just access the data objects slightly different (but right) way than you did:
<ul ng-repeat = "country in countryType">
<li ng-repeat="details in country.data.cities">
<span> {{details.name}} </span>
<span> {{details.rank}}</span>
</li>
</ul>
And everything should work.

combobox and angularjs using ng-options

My data structure is following
{
"Name": "Somename",
"SchoolSeasons": [
{
"Id": "1",
"Name": "2014/2015"
},
{
"Id": "2",
"Name": "2013/2014"
}
]
}
using angularjs inside html view I want to render this year inside combobox for selection. Tried following
<div ng-repeat="seasson in data.SchoolSeasons">
<select ng-model="seasson.Name"
ng-options="seasson.Name for seasson in session.Name">
</select>
</div>
any idea?
Given:
$scope.data = {
"Name": "Somename",
"SchoolSeasons": [{
"Id": "1",
"Name": "2014/2015"
}, {
"Id": "2",
"Name": "2013/2014"
}]
};
Should just be as simple as:
<select ng-model="seasson.Name" ng-options="seasson.Name for seasson in data.SchoolSeasons">
<option value="">-- choose season --</option>
</select>
Example here.

Categories