How to output elements in a JSON array with AngularJS
33,243
Solution 1
Change your json array in scope like;
$scope.faq = [
{key: "Question 1",
value: "Answer1"},
{key: "Question 2",
value: "Answer2"}
];
And in your view;
<div ng-repeat="f in faq">
{{f.key}}-{{f.value}}
</div>
Solution 2
Due to it being within an array, you will have to loop through the key values of each object.
http://fiddle.jshell.net/TheSharpieOne/QuCCk/
<div ng-repeat="value in faq">
<div ng-repeat="(question,answer) in value">
{{question}} - {{answer}}
</div>
</div>
Alternately:
If you have just a simple object:
$scope.faq = {
"Question 1": "Answer1",
"Question 2": "Answer2"
};
You could avoid the second repeat
<div data-ng-repeat="(question,answer) in faq">
{{question}} - {{answer}}
</div>
http://fiddle.jshell.net/TheSharpieOne/D3sED/
Author by
Robert Christian
Software architect and polyglot developer currently using S/O for the Java, Python, NodeJS, Javascript, Vert.x, client MVC frameworks, open source, cloud platform, and algorithms communities.
Updated on July 09, 2022Comments
-
Robert Christian almost 2 years
JSON array defined in scope:
$scope.faq = [ {"Question 1": "Answer1"}, {"Question 2": "Answer2"} ];
HTML:
<div ng-repeat="f in faq"> {{f}} </div>
Output:
{"Question 1": "Answer1"} {"Question 2": "Answer2"}
What I want output to look like:
Question 1 - Answer1 Question 2 - Answer2
How it seems like it should work:
<div ng-repeat="f in faq"> {{f.key}}-{{f.value}} </div>
... but it doesn't.
-
Robert Christian over 10 yearsThis falls down when question is a dynamic value, which it is in the non-trivial, example case.
-
Robert Christian over 10 yearsPerfect, this works. I like the alternative: <div ng-repeat="(question, answer) in faq"> {{question}} - {{answer}} </div>, which doesn't require adding key/value, but I think this is more extensible and closer to answering the question.
-
Majki over 10 yearsWhile working I find it far from being concise and readable. As you have also noticed yourself - adding unrelated keys to your object would break this ngRepeat, which means it's not a good design.