如何使用 angular 访问 HTML 中的 JSON 数组对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28175381/
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
How to access JSON array object in HTML using angular?
提问by CountGradsky
I have a JSON file and I want to display it in my HTML. But I dont know how to use the syntax for deeply nested objects.
我有一个 JSON 文件,我想在我的 HTML 中显示它。但我不知道如何使用深度嵌套对象的语法。
{
"questions": [
{
"question": "Qw1",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
},
{
"question": "Qw2",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
}
]
}
I am not trying to use ng-repeat, as I need to access them them one by one.
我不是要使用 ng-repeat,因为我需要一一访问它们。
<div class="main-content" ng-controller="QuestionCtrl">
<div id="Content1">
<h1>Question 1</h1>
<p>{{questions.question[1].answer}}</p>
...........
Ofcourse it doesn't work. How do I acces my information?
当然是行不通的。我如何访问我的信息?
回答by Radim K?hler
There is a working plunker
有一个工作plunker
Using this controller:
使用这个控制器:
.controller('QuestionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.questions = [];
$http
.get("data.json")
.then(function(response){
$scope.questions = response.data.questions;
});
}])
which is loading your data, we can use this
正在加载您的数据,我们可以使用它
<div class="main-content" ng-controller="QuestionCtrl">
<div id="Content1">
<h1>Question 1</h1>
<p>{{questions[0].question}}</p>
<p>{{questions[0].answers[0]}}</p>
<p>{{questions[0].answers[1]}}</p>
</div>
</div>
Or we can use it like this:
或者我们可以这样使用它:
<h1>Question 1</h1>
<p>{{questions[0].question}}</p>
<h2>answer 1</h2>
<p>{{questions[0].answers[0].value}}</p>
<p>{{questions[0].answers[0].answers}}</p>
<h2>answer 2</h2>
<p>{{questions[0].answers[1].value}}</p>
<p>{{questions[0].answers[1].answers}}</p>
which will show the numeric value
and answers
text
这将显示数字value
和answers
文本
Check it here in action
回答by vikvincer
<div class="main-content" *ngFor="let q of questions">
<h1> {{q.question}}</h1>
<p *ngFor="let ans of q.answers">{{ans.answers}} = {{ans.value}} </p>
</div>
回答by Matt Ball
questions
is the array, not questions.question
, and your JSON does not contain answer
properties. Did you try using the correct traversal?
questions
是数组,而不是questions.question
,并且您的 JSON 不包含answer
属性。您是否尝试使用正确的遍历?
questions[0].answers[0].value
should get you 25
.
应该得到你25
。