user6934713 user6934713 - 17 days ago 8
AngularJS Question

Ng-repeat with condition

I am trying to iterate in json with question and answers. For each question I have multiple answers. I would like to show each question with the multiple answers. I would like to display. Thank you in advance for the help.

q1
a1.1
a1.2
q2
a2.1
a2.3
q3
a3.1
a3.2
a3.3


The json look like:

[{"QuestionID":101,"Question":"q1","Response":"a1.1","CorrectResponse":false},
{"QuestionID":101,"Question":"q1","Response":"a1.2","CorrectResponse":true},
{"QuestionID":102,"Question":"q2","Response":"a2.1","CorrectResponse":false},
{"QuestionID":102,"Question":"q2","Response":"a2.2","CorrectResponse":true},
{"QuestionID":103,"Question":"q3","Response":"a3.1","CorrectResponse":false},
{"QuestionID":103,"Question":"q3","Response":"a3.2","CorrectResponse":true},
{"QuestionID":103,"Question":"q3","Response":"a3.3","CorrectResponse":true}]


This is my code so far

var questions = [];

var answersWithCorrectCheck = [];


questions.push(test[0].Question);
answersWithCorrectCheck.push({ answer: test[0].Response, correct: test[0].CorrectResponse });

for (i = 1; i < test.length; i++)
{
if(test[i - 1].QuestionID !== test[i].QuestionID )
{
questions.push(test[i].Question);
}

answersWithCorrectCheck.push({ answer: test[i].Response, correct: test[i].CorrectResponse });
}

$scope.displayQuestionsPerTest = questions;
$scope.answersWithCorrectResonse = answersWithCorrectCheck;

Answer

You can do this with angular-filter,

<body ng-app="DemoApp" ng-controller="DemoController">
  <ul ng-repeat="(key, value) in data | groupBy: 'Question'">
    Question name: {{ key }}
    <li ng-repeat="answer in value">
      {{ answer.Response }}
    </li>
  </ul>
</body>

DEMO