简体   繁体   中英

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.

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>

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/

$scope.faq = [
    "Answer1",
    "Answer2"
];


<div ng-repeat="answer in faq">
    Question {{$index+1}}-{{answer}}
</div>

If you are using ECMA5 compliant browsers, you could try,

<div ng-repeat="f in faq">
    {{Object.keys(f)[0]}}-{{f[Object.keys(f)[0]]}}
</div>

Of course, this will only work reliably if your object only has 1 key. If it has more than one key, your best bet will be to write a filter function that gets the key names, which you can then use to extract the relevant keys.

Check my code: http://plnkr.co/edit/NGEcK7iieFRtvt7WP48A?p=preview

ng-repeat needs an array, for each object in the array, you need keys bound with values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM