我有一个 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
}
]
}
]
}
我不想使用 ng-repeat,因为我需要一个一个地访问它们。
<div class="main-content" ng-controller="QuestionCtrl">
<div id="Content1">
<h1>Question 1</h1>
<p>{{questions.question[1].answer}}</p>
...........
当然不行。我如何访问我的信息?
最佳答案
使用这个 Controller :
.controller('QuestionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.questions = [];
$http
.get("data.json")
.then(function(response){
$scope.questions = response.data.questions;
});
}])
正在加载您的数据,我们可以使用它
<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>
或者我们可以这样使用它:
<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>
这将显示数字值
和答案
文本
关于html - 如何使用 Angular 访问 HTML 中的 JSON 数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28175381/