Pallavi Mistry Pallavi Mistry - 5 months ago 9
jQuery Question

Handling selectedValues from Multiple drop-downs using ng-repeat and ng-options



<li ng-repeat="questionAndAnswers in questionnaire">
<select ng-model="selectedAnswer" ng-options="answer as answer.displayText for answer in questionAndAnswers.answers track by answer.value" ng-change="validateAnswers()">
</select>
</li>







"questionAndAnswer": [{
"question": "Is your camera fully functional?",
"answers": [{
"displayText": "Yes, everything works",
"value": "Success"
}, {
"displayText": "Some of the buttons are broken",
"value": "Failure"
}]
}, {
"question": "Does your camera has any obvious damage?",
"answers": [{
"displayText": "No it's perfect",
"value": "Success"
}, {
"displayText": "Yes, there is heavy damage",
"value": "Failure"
}]
}]





I am creating multiple drop-downs based on the size of questionaire (json sample given) using ng-options and ng-repeat. Could someone please suggest the best angular way to get the answers in validateAnswers() javascript where I may validate if the user has selected "Success" answer. If all the answers are Success, I would need to display a success message.

Answer

I would use $index to store the answers in an array and validate the array in the validateAnswer function.

In your html : minor tweek :

<li ng-repeat="questionAndAnswers in questionnaire track by $index">
   {{questionAndAnswers.question}}<br>
   <select ng-model="selectedAnswers[$index]" ng-options="answer.value as answer.displayText for answer in questionAndAnswers.answers" ng-change="validateAnswers()">
   </select>
 </li>

In your controller :

$scope.questionnaire = [{
  "question": "Is your camera fully functional?",
  "answers": [{
    "displayText": "Yes, everything works",
    "value": "Success"
  }, {
    "displayText": "Some of the buttons are broken",
    "value": "Failure"
  }]
}, {
  "question": "Does your camera has any obvious damage?",
  "answers": [
  {
    "displayText": "No it's perfect",
    "value": "Success"
  }, 
  {
    "displayText": "Yes, there is heavy damage",
    "value": "Failure"
  }]
}];

$scope.selectedAnswers = [];  

$scope.validateAnswers = function() {
  console.log($scope.selectedAnswers);
  var allSuccess = true;
  for (i = 0; i < $scope.questionnaire.length; i++) { 
    allSuccess = allSuccess && ($scope.selectedAnswers[i] === 'Success');
  }
  if (allSuccess) {
    $scope.result = 'Congratz! All answers correct!';
  } else {
    $scope.result = '';
  }
}

Here is a working example in Plunker

Personally I would use booleans as value for your answers instead of strings 'Success' and 'Failure' if you only have these two values.

Hope this will help you out.