如何使用AngularJS访问嵌套的JSON值

时间:2016-07-07 16:21:47

标签: html angularjs json

我使用AngularJS应用程序。我尝试从level1question一次访问一个问题及其选项。实际上我无法访问问题及其选项。

  

JSON

{
 "_id":1,
 "level1question":[
        {
         "question": "Which one is correct team name in NBA?",
         "options": [
                     "New York Bulls",
                     "Los Angeles Kings",
                     "Golden State Warriros",
                     "Huston Rocket"
                    ],
         "result": 3
        },
         {
         "question": "5 + 7 = ?",
         "options": [
                     "10",
                     "11",
                     "12",
                     "13"
                    ],
         "result": 2,
       },
        {
         "question": "12 - 8 = ?",
         "options": [
                     "1",
                     "2",
                     "3",
                     "4"
                    ],
         "result": 3
         }
    ]
}
  

HTML

<div>
    {{currentQ.question}}
</div>
<div class="buttonMCQ">
    <button class="ans"
            ng-repeat="option in currentQ.options">
      {{option}}
    </button>
</div>
  

AngularJS控制器

$http.get('http://v1/level.json').success(function(res){
     $scope.myData = res;
     jsonData = $scope.myData;
     $scope.currentQ = jsonData[next];
}).error(function (err){
     console.log(err);
});

1 个答案:

答案 0 :(得分:0)

从提供的有限的JS代码中,很难确切地说出你想要做什么,但是我认为你正在寻找here is a DEMO

HTML

<body ng-app="myApp" ng-controller="myCtrl">
    <div>
    {{currentQ.question}}
    </div>
    <div class="buttonMCQ">
      <button class="ans" ng-click="nextQuestion()" ng-repeat="option in currentQ.options">
          {{option}}
        </button>
    </div>
</body>

JS

var app = angular.module("myApp", [])
.controller("myCtrl", function ($http, $scope) {
  var next = 0;
  $scope.getNextQuestion = function () {
    $http.get('level.json').success(function(res){
       $scope.myData = res;
       jsonData = $scope.myData;
       console.log(jsonData["level1question"][next]);
       $scope.currentQ = jsonData["level1question"][next];
    }).error(function (err){
         console.log(err);
    });
  };
  $scope.getNextQuestion();

  $scope.nextQuestion = function () {
    next = (next + 1) % 3;
    $scope.getNextQuestion();
  }
});

JSON

{
 "_id":1,
 "level1question":[
    {
    "question": "Which one is correct team name in NBA?",
    "options": [
               "New York Bulls",
               "Los Angeles Kings",
               "Golden State Warriros",
               "Huston Rocket"
              ],
    "result": 3
    },
    {
    "question": "5 + 7 = ?",
    "options": [
               "10",
               "11",
               "12",
               "13"
              ],
    "result": 2
    },
    {
      "question": "12 - 8 = ?",
      "options": [
                 "1",
                 "2",
                 "3",
                 "4"
                ],
      "result": 3
    }
  ]
}