Binding json arrays in angular js select option - javascript

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

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 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>
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

Angular, How to filter through json using Angular?

I have a simple Json and I need to filter the objects based on a name, In this example I have two movie titles "Paddington" and "Interstaller" and lets say I only want to filter out by name "Paddington" and set the $scope only to the first item "Paddington" item
{
"feed": {
"author": {
"name": {
"label": "iTunes Store"
},
"uri": {
"label": "http://www.apple.com/itunes/"
}
},
"entry": [
{
"im:name": {
"label": "Paddington"
},
"im:image": [
{
"label": "url1",
"attributes": {
"height": "60"
}
},
{
"label": "url2",
"attributes": {
"height": "60"
}
},
{
"label": "url3",
"attributes": {
"height": "170"
}
}
]
},
{
"im:name": {
"label": "Interstellar"
},"im:image": [
{
"label": "url4",
"attributes": {
"height": "60"
}
},
{
"label": "url5",
"attributes": {
"height": "60"
}
},
{
"label": "url6",
"attributes": {
"height": "170"
}
}
]
}
],
"updated": {
"label": "2015-04-18T11:29:36-07:00"
},
"rights": {
"label": "Copyright 2008 Apple Inc."
},
"title": {
"label": "iTunes Store: Top Movies"
}
}
My code
app.controller('movieController', function ($scope, $routeParams, movieService) {
$scope.filterData = function init(){
$scope.movies = movieService.get({id: 4403});// returns the json
var filtered = $filter('filter')($scope.movies.entry, function(value,index){
return value["im:name"].label.indexOf("The Sound")!=-1;
});
$scope.firstItem = filtered[0];
};
alert($scope.firstItem);
});
app.factory('movieService',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {id: '#id'});
});
The $filter service will let you fetch a filter function, there is a filter function called 'filter' that is built in. Documentation here:
https://docs.angularjs.org/api/ng/filter/filter
app.controller('movieController', function ($scope, $filter, $routeParams, movieService) {
alert($routeParams.movieID);
$scope.movies = movieService.get({id: 4403});// returns the json
$scope.movies.$promise.then(function(resp){
var filterFunc = $filter('filter');
var filtered = filterFunc($scope.movies.feed.entry, function(value,index){
return value["im:name"].label.indexOf($routeParams.movieID)!=-1;
});
$scope.firstItem = filtered[0]; // could put this in place of movies but it's confusing since you're re-using that name for the initial resource and this filtered item
});
function test() {
alert(movieService.get({id: 4403}).entry.summary.label);
};
$scope.movies.name = {}; // need to return Paddington
$scope.movies.url = {}; // need to return url3
});
app.factory('movieService',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {id: '#id'});
});
There isn't an AngularJS-specific solution to this problem, it's a generic JavaScript issue. You want to loop through each object in the JSON dictionary and then check the title.
Something like this:
data = {
'feed': {
'entry': [
{'im:name': 'Paddington'},
{'im:name': 'Interstellar'},
]
}
}
$scope.movies.name = null;
for (var i = 0; i < data.feed.entry.length; i += 1) {
var movie = data.feed.entry.entry[i];
if (movie['im:name'].indexOf('Paddington') !== -1) {
$scope.movies.name = movie.title;
break;
}
}
You can also use the angular.forEach function.

Filtering in Angular JS by map keys

Consider the following JSON structure:
UPDATED:
[
{
"game0001": {
"-JfuVKIsUBH27DMJfWmL": {
"action": "STARTFIRSTHALF",
"team": "HOME"
},
"-JfuVLJGMgclLZ0Maduh": {
"action": "GOAL",
"team": "AWAY"
}
},
"$id": "events",
"$priority": null
},
{
"game0001": {
"gameRunning": false,
"startDate": "17/01/2015 17:27:42 PM"
},
"game0002": {
"gameRunning": true,
"startDate": "17/01/2015 19:45:59 PM"
},
"game0003": {
"gameRunning": false,
"scheduledDate": "17/01/2014 12:30:00 PM"
},
"$id": "games",
"$priority": null
}
]
How can I achieve filtering in AngularJS in HTML?
In a very basic way, what I'm trying to achieve is the following:
<div ng-repeat="game in games">
<div ng-repeat="event in events | filter:game">
{{event.name}} - {{game.name}}
</div>
</div>
I have 2 maps games and events which share the same keys, e.g (game0001, game0002)
While repeating the games, I would like to have a inner repeater for events and filter only the ones sharing the same key/id.
Here's a working plunkr, I made assumptions about the data you wanted to fetch:
http://plnkr.co/edit/DVwQaRZeZiagGEzY4lCy?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.games = {
"games": {
"game0001": {
"first": "a",
"second": "b"
},
"game0002": {
"first": "c",
"second": "d"
}
}
}
$scope.gamesKeys = Object.keys($scope.games['games']);
$scope.events = {
"events": {
"game0001": {
"event": {
"key": "a"
},
"event": {
"key": "b"
},
"event": {
"key": "c"
}
},
"game0002": {
"event": {
"key": "a"
},
"event": {
"key": "b"
},
"event": {
"key": "c"
}
}
}
}
$scope.eventsKeys = Object.keys($scope.events['events']);
});
The important part is the ng-repeat here:
<body ng-controller="MainCtrl">
<div ng-repeat="gameKey in gamesKeys">
<div ng-repeat="eventKey in eventsKeys">
event: {{events['events'][eventKey].event.key}} - game: {{games['games'][gameKey].first}}
</div>
</div>
</body>

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