Sau_Patil Sau_Patil - 5 months ago 20
JSON Question

How to access Nested JSON value using AngularJS

I work with an AngularJS application. I am try to access one question and its options at a time from level1question. Actually I am not able to get access the question and its options.


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 Controller


$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);
});

Answer

From the limited JS code provided, it is hard to tell exactly what you are trying to do, but here is a DEMO of what I think you are looking for.

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
    }
  ]
}