My Spring Rest Controller Endpoint is as below:
#CrossOrigin
#RequestMapping(value = "/getEverything", method=RequestMethod.GET)
public #ResponseBody MyItems getEverything(){
return myService.getEverything();
}
Below is MyItems class:
public class MyItems {
private Map<String, ArrayList<MyItem>> everything;
public Map<String, ArrayList<MyItem>> getEverything() {
return everything;
}
public void setEverything(Map<String, ArrayList<MyItem>> everything) {
this.everything = everything;
}
}
The rest call returns Json in below format:
{
"myItems": {
"Office": [
{
"field1": "Read a book",
"field2": "xyz",
"field3": true,
"field4": 1489795200000
},
{
"field1": "Write a program",
"field2": "abc",
"field3": false,
"field4": 1489881600000
}
],
"Home": [
{
"field1": "Watch a movie",
"field2": "pqr",
"field3": true,
"field4": 1489797800000
}
]
}
}
Here Office, Home are keys in the returned map.
How do I iterate or consume this JSon in AngularJS?
How do I get the key values ?
$http.get(REST_SERVICE_URI + 'toDo/getAllItems').then(function(response){
// what will go here ?
$scope.myItemLists = response.data;
});
I want myItemLists as a List containing objects with two properties:
1) Listname: This will be the key of the map returned.
2) List of Fields: This will be the list of object returned.
Thanks!
Try like this. use angular forEach loop
var app = angular.module('app', []);
app.controller('aCtrl', function($scope) {
$scope.myItems ={
"myItems": {
"Office": [
{
"field1": "Read a book",
"field2": "xyz",
"field3": true,
"field4": 1489795200000
},
{
"field1": "Write a program",
"field2": "abc",
"field3": false,
"field4": 1489881600000
}
],
"Home": [
{
"field1": "Watch a movie",
"field2": "pqr",
"field3": true,
"field4": 1489797800000
}
]
}
}
var keys = [];
var objectValues = [];
angular.forEach($scope.myItems.myItems,function(value,key){
keys.push(key);
objectValues.push(value);
})
console.log(keys);
console.log(objectValues);
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="aCtrl">
</div>
you can store data in separate variable see below,
$http.get(REST_SERVICE_URI + 'toDo/getAllItems').then(function(response){
// what will go here ?
$scope.myItemLists = response.data;
$scope.itemListOfficeData = response.data.myItems.Office;
$scope.itemListHomeData = response.data.myItems.Home;
});
Or you can use nested data-ng-repeat for iterate data see below link for reference.
Nested ng-repeat
using ng-repeat inside another ng-repeat
While HJz answer is fine if what you want is to iterate through your json data in the controller, but if you simply want to present the data in a view, you can use ng-repeat directly on your json object like this:
<ul>
<li ng-repeat="(key, value) in myItems">{{key}}: {{value | json}}</li>
<ul>
which roughly turns into the following html (some values have been ignored for better readability):
<ul>
<li>Office: [{"field1": "Read a book"}, {"field1": "Read a book"}]</li>
<li>Home: [{"field1": "Watch a movie"}]</li>
<ul>
You can nest this ng-repeat directives, to further iterate through the values in your json data.
Alternatively, if all you need is an array of keys or an array of values, then JavaScript got functions you can use to extract those:
var keys = Object.keys(myItems);
// -> ['Office', 'Home']
var values = Object.values(myItems);
// -> [[{"field1": "Read a book"}, {"field1": "Write a program"}], [{"field1": "Watch a movie"}]]
You can flatten the nested object first and then iterate over it or you can use nested ng-repeat as shown below:
var app = angular.module('app', []);
app.controller('aCtrl', function($scope) {
var items = {
"myItems": {
"Office": [{
"field1": "Read a book",
"field2": "xyz",
"field3": true,
"field4": 1489795200000
},
{
"field1": "Write a program",
"field2": "abc",
"field3": false,
"field4": 1489881600000
}
],
"Home": [{
"field1": "Watch a movie",
"field2": "pqr",
"field3": true,
"field4": 1489797800000
}]
}
}
$scope.myItems = items.myItems;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="aCtrl">
<ul>
<li ng-repeat="(item, fields) in myItems">
{{item}}
<ul>
<li ng-repeat="field in fields">
{{field}}
<ul>
<li ng-repeat="(name, value) in field">
{{name}}:{{value}}
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Related
how can I get the information from this json to paint them in angular 10
{
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}
for normal jsons I used this one, but that jeson has 2 arrays and it won't let me
return this.http.get<Country[]>("./assets/data.json");
Error trying to diff '[object Object]'. Only arrays and iterables are allowed
<!-- html -->
<div *ngFor="let item of countri">
{{item.id}}
</div>
model
export interface Country {
id: number;
name: string;
}
and my subscribe
countri: Country[] = [];
this.countriesService.getCountries().subscribe(
countri => {
this.countri = countri;
console.log(countri);
},
err => console.log(err)
);
Use any.
1st way:
return this.http.get<any>("./assets/data.json");
2nd way define an proper interface for your data.
export interface IRequest {
countries: ICourtry[],
states: IState[]
}
export interface ICourtry{
id:number;
name: string;
}
export interface IState{
id:number;
name: string;
countryId: number;
}
return this.http.get<IRequest>("./assets/data.json");
This mentioned error(Error trying to diff '[object Object]') are because you are using this json somewhere in your template but it has no values. Hope it will fix it or provide the template code also.
Error trying to diff '[object Object]'. Only arrays and iterables are allowed , this error usually comes when you try to iterate through ngFor with an Object instead of an Array.
If you are using ngFor,
list.component.ts
data={
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}
list.component.html
<ul>
<li *ngFor="let item of data.countries">
{{item.name}}
</li>
</ul>
or
<ul>
<li *ngFor="let item of data.states">
{{item.name}}
</li>
As the error suggests, you are most likely trying to iterate over an object rather than an array. Also, since the data you fetch is asynchronous you may make use of the following code to avoid any errors. It makes use of the async pipe along with the safe(?) operator.
.ts
jsonData;
ngOnInit() {
this.jsonData = this.http.get('./assets/data.json');
}
template
<div *ngFor="let country of (jsonData | async)?.countries">
{{ country | json}}
</div>
<div *ngFor="let state of (jsonData | async)?.states">
{{ state | json}}
</div>
I'm trying to filter a nested array of objects with my own objects, by idSubject. But I'm not getting the right result.
I have articles (which have subjects)
And a array of objects (which are the subjects I want to filter the articles with)
Data looks like this:
So I'm trying to filter the array of articles by its subjects.
I tried the following:
<div class="panel panel-default"
ng-repeat="searchArticle in searchArticles | filter: {subjects: filterSubjects} as articleSearchResult">
So filterSubjects is the second screenshot and SearchArticles is the first screenshot.
Without much luck.
Hope you can help, please tell me if things are still unclear.
This custom filter will help you.
Example : http://plnkr.co/edit/jMizCLxPH6DtDA5wL15Q?p=preview
HTML:
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<h2>Select Subjects</h2>
<div ng-repeat="subject in subjects">
<label>
<input type="checkbox" ng-model="filterSubjects[subject.id]" ng-true-value="'{{subject.id}}'" ng-false-value="''">{{subject.name}}</label>
</div>
<h2>Filtered Articles</h2>
<div ng-repeat="searchArticle in searchArticles | subjectFilter:filterSubjects">{{searchArticle.name}}</div>
</div>
</body>
JS:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.searchArticles = [{
"name": "Article1",
"sid": "1"
}, {
"name": "Article2",
"sid": "1"
}, {
"name": "Article3",
"sid": "2"
}];
$scope.subjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject2",
"id": "2"
}];
$scope.filterSubjects = [];
});
app.filter('subjectFilter', function() {
return function(articles, filterSubjects) {
filtered = articles.filter(function(e){return filterSubjects.indexOf(e.sid) >= 0},filterSubjects);
return filtered;
}
});
if you want to filter based on object :
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.searchArticles = [{
"name": "Article1",
"sid": "1"
}, {
"name": "Article2",
"sid": "1"
}, {
"name": "Article3",
"sid": "2"
}];
$scope.subjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject2",
"id": "2"
}];
$scope.filterSubjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject1",
"id": "2"
}];
});
app.filter('subjectFilter', function() {
return function(articles, filterSubjects) {
var sFiltered = [];
for (var i = 0; i < filterSubjects.length; i++) {
sFiltered.push(filterSubjects[i].id);
}
var filtered = articles.filter(function(e) {
return sFiltered.indexOf(e.sid) >= 0;
}, sFiltered);
return filtered;
}
});
I have an object, which has objects inside, and arrays in child objects. Here's the structure:
var keywords = {
"Animals" : {
"Pets" : [
"Guppy", "Parrot", "Goldfish", "Dog", "Cat"
],
"Wild animals" : [
"Tiger", "Ant", "Tetra", "Peafowl", "Mongoose"
],
"Domestic animals" : [
"Cow", "Pig", "Goat", "Horse"
]
},
"Food" : {
"Fast food" : [
"Cheeseburger", "Hamburger"
],
"Dessert" : [
"Chocolate", "Cookie", "Cake", "Pie"
]
},
"Vehicle" : {
"Motorcycle" : [
"Harley Davidson"
],
"Car" : [
"Lamborghini", "Ferrari", "Bugatti", "BMW", "Mercedes"
]
},
"Movie" : {
"Science fiction" : [
"Sunshine", "Interstellar", "The Moon", "Oblivion", "Star Trek", "Star Wars"
]
}
};
I've made a foreach loop for looping through the elements inside and print them on screen:
angular.forEach(keywords, function(value, key) {
console.log(key);
angular.forEach(value, function(value, key) {
console.log(key);
angular.forEach(value, function(value, key) {
console.log(value);
})
})
})
Now, I'm trying to do the same with ng-repeat directive on a div (that has a div in it, and another in the child div), but can't make it work, have no clue how to start it. Any idea?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.keywords = {
"Animals": {
"Pets": [
"Guppy", "Parrot", "Goldfish", "Dog", "Cat"
],
"Wild animals": [
"Tiger", "Ant", "Tetra", "Peafowl", "Mongoose"
],
"Domestic animals": [
"Cow", "Pig", "Goat", "Horse"
]
},
"Food": {
"Fast food": [
"Cheeseburger", "Hamburger"
],
"Dessert": [
"Chocolate", "Cookie", "Cake", "Pie"
]
},
"Vehicle": {
"Motorcycle": [
"Harley Davidson"
],
"Car": [
"Lamborghini", "Ferrari", "Bugatti", "BMW", "Mercedes"
]
},
"Movie": {
"Science fiction": [
"Sunshine", "Interstellar", "The Moon", "Oblivion", "Star Trek", "Star Wars"
]
}
};
});
.section1{
background-color: CornflowerBlue;
}
.section2{
background-color: lightblue;
}
.section3{
background-color: Azure ;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="(keyword, list) in keywords" class="section1">
{{keyword}}
<div ng-repeat="(name, items) in list" class="section2">
{{name}}
<div ng-repeat="item in items" class="section3">
{{item}}
</div>
</div>
</div>
</body>
I think we are not using ng-repeat with this type of array.
You should go throw with this logic.
$scope.html ="";
angular.forEach(keywords, function(value, key) {
$scope.html += "<div>"+ key ;
angular.forEach(value, function(value, key) {
$scope.html += "<div>"+ key ;
angular.forEach(value, function(value, key) {
$scope.html += "<div>"+ key + "</div>";
})
$scope.html += "</div>";
})
$scope.html += "</div>";
})
and Print 'html' scope into your HTML page.
{{html}}
I know this is not perfect solution but it's trick to fix you current problem.
response object like
$scope.list= [
Object {
cid=74,
date="2016-08-25T00:00:00.000+0530",
optkey="key",
optvalue="{
value:{
'name':test,
'gender':male
}
}"
},
Object {
cid=75,
date="2016-08-25T00:00:00.000+0530",
optkey="key",
optvalue="{
value:{
'name':test2,
'gender':female
}
}"
}},
Object {
cid=77,
date="2016-08-26T00:00:00.000+0530",
optkey="key",
optvalue="{
value:{
'name':test1,
'gender':female
}
}"
}]
and in html page used ng-repeat
<div ng-repeat="item in list">
{{item.date}} -- works fine
</div>
here how to display json value in object optvalue, done some code like.
<div ng-repeat="item in list">
{{item.optvalue.value}} -- but it is undefined
</div>
but it is not working can any one give hint for this
Just because your optvalue is a String but not a object. It should be :
optvalue = {
value:{
'name':test1,
'gender':female
}
}
In JSON, an object should NOT be in the parenthese.
Try this working example, please check the object created.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.list=
[
{
cid:74, date:"2016-08-25T00:00:00.000+0530", optkey:"key", optvalue:{value:{'name':'test','gender':'male'}}
},
{
cid:75, date:"2016-08-25T00:00:00.000+0530", optkey:"key", optvalue:{value:{'name':'test','gender':'male'}}
},
{
cid:76, date:"2016-08-25T00:00:00.000+0530", optkey:"key", optvalue:{value:{'name':'test','gender':'male'}}
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="item in list">
{{item.optvalue.value.name}}
</div>
</div>
The response JSON is not valid :
Strings should be wrapped in double quotes.
Expecting colon, not = in key value pairs.
Invalid characters found.
Invalid number.
Issue Capture :
Valid JSON :
[
{
"cid": 74,
"date": "2016-08-25T00:00:00.000+0530",
"optkey": "key",
"optvalue": {
"value": {
"name": "test",
"gender": "male"
}
}
},
{
"cid": 75,
"date": "2016-08-25T00:00:00.000+0530",
"optkey": "key",
"optvalue": {
"value": {
"name": "test2",
"gender": "female"
}
}
},
{
"cid": 77,
"date": "2016-08-26T00:00:00.000+0530",
"optkey": "key",
"optvalue": {
"value": {
"name": "test1",
"gender": "female"
}
}
}
]
In your case {{item.optvalue.value}} is giving undefined because optvalue is a string not an object.So, it should be an object.
"optvalue": {
"value": {
"name": "test1",
"gender": "female"
}
}
thanks for your answers,i have resolved it using--
angular.toJson and angular.fromJson
while send to server used
angular.toJson(stringOfJson)
and when got the response object the using
angular.fromJson(value)
and set to object field,it is working fine.
you need to change your code to this
<div ng-repeat="item in list">
{{item.optvalue.value.name}}
</div>
I am newbie to AngularJS. I have JSON file which I have to fetch using angularjs!
JSON File
{
"records": [
{
"students": [
{
"id": 1,
"name": "Bill",
},
{
"id": 2,
"name": "Steve",
}
],
"exstudent": [
{
"id": 1,
"name": "Woz",
},
{
"id": 2,
"name": "Jonathan",
}
]
}
]
}
Controller part snippet -
$http.get('json/somedata.json').success(function (data){
$scope.name = data.records.student.name;
$scope.exname = data.records.exstudent.name;
});
}])
HTML
<div class="panel-body" ng-repeat = "browse in name">
{{browse.student.name}}
</div>
Which part I am doing wrong? I think the problem is with ng-repeat!
Need Help
You can't use data.records.students.name as students is an Array.
You can however store its data into your $scope and use it in the ng-repeat:
$http.get('json/config.json').success(function (data){
$scope.students = data.records.students;
$scope.exstudents = data.records.exstudent;
});
Then in your HTML use the ng-repeat like this:
<div class="panel-body" ng-repeat="student in students">
{{student.name}}
</div>