html - 如何使用 Angular 访问 HTML 中的 JSON 数组对象?

标签 html arrays json angularjs

我有一个 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>
                  ...........

当然不行。我如何访问我的信息?

最佳答案

有一个working plunker

使用这个 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>

这将显示数字答案 文本

查一下here in action

关于html - 如何使用 Angular 访问 HTML 中的 JSON 数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28175381/

相关文章:

java - JsonArray.getvaluesAs 不以 String.class 作为参数

java - 使用JAVA高效查找JSON中的键值

javascript - 如何从我的 html 文件移动到另一个 html 文件以创建 iOS 混合应用程序?

html - 使用 Bootstrap 防止缩放缩放

html - 如何用 css 替换 <select> 元素上的箭头按钮?

javascript - 聪明的 "add tag"需要 javascript 帮助

arrays - 如何使用 PostgreSQL 更新 JSON 数组

php - 如果你有菜单数组,如何设置 wordpress 菜单

python - 使用Python从嵌套json字典获取信息的问题

javascript - 如何使用 JSON 检索 OpenWeatherMap 数据?