How to output elements in a JSON array with AngularJS

一个人想着一个人 提交于 2019-12-04 09:33:57

问题


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.


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



回答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/




回答3:


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


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



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/18436084/how-to-output-elements-in-a-json-array-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!