Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output elements in a JSON array with AngularJS

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.

like image 522
Robert Christian Avatar asked Aug 26 '13 03:08

Robert Christian


2 Answers

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>
like image 57
BKM Avatar answered Nov 04 '22 22:11

BKM


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/

like image 20
TheSharpieOne Avatar answered Nov 04 '22 22:11

TheSharpieOne