admin管理员组文章数量:1297226
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.
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.
Share Improve this question asked Aug 26, 2013 at 3:13 Robert ChristianRobert Christian 18.3k20 gold badges76 silver badges90 bronze badges5 Answers
Reset to default 12Change 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.
本文标签: javascriptHow to output elements in a JSON array with AngularJSStack Overflow
版权声明:本文标题:javascript - How to output elements in a JSON array with AngularJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738425313a2086091.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论