Html 如何使用 AngularJS 输出 JSON 数组中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18436084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:36:23  来源:igfitidea点击:

How to output elements in a JSON array with AngularJS

javascripthtmljsonangularjsoutput

提问by Robert Christian

JSON array defined in scope:

范围内定义的 JSON 数组:

$scope.faq = [
        {"Question 1": "Answer1"},
        {"Question 2": "Answer2"}
    ];

HTML:

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.

......但它没有。

回答by BKM

Change your json array in scope like;

在范围内更改您的 json 数组,例如;

$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>

回答by TheSharpieOne

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/

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/

http://fiddle.jshell.net/TheSharpieOne/D3sED/

回答by gos1

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

如果您使用的是符合 ECMA5 标准的浏览器,您可以尝试,

<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.

当然,这只有在您的对象只有 1 个键时才能可靠地工作。如果它有多个键,最好的办法是编写一个过滤器函数来获取键名,然后您可以使用它来提取相关的键。

回答by Z.T. Yang

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

检查我的代码:http: //plnkr.co/edit/NGEcK7iieFRtvt7WP48A?p=preview

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

ng-repeat 需要一个数组,对于数组中的每个对象,您都需要绑定值的键。

回答by Fly_pig

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


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