I am trying to create dynamic forms based on servers response. For example, I have 8 buttons, and each button when clicked should generate a different questionnaire with different input types. The questions for each category are grabbed from the back-end and each question has its type along with it, which could be radio, select etc. Based on this information, how can I generate forms for a specific question set depending what button a user clicks. One thing I thought of was to use ng-hide/show depending on what category is clicked but that would be a really bad practice as there are in total 64 questions for the 8 categories(8 each). Any help would be appreciated. Thanks!!
The response is like:
{
"code": 200,
"data": {
"id": "598ca3dac405bc378fc21764",
"question_set_number": "QS1",
"questions": [
{
"answers": [
"Answer 1",
"Answer 2",
"Answer 3"
],
"id": "59839d20c405bc411540a11d",
"question_number": "Q1",
"question_text": "Test question",
"type": "radio"
},
{
"answers": [
"Answer 1",
"Answer 2",
"Answer 3"
],
"id": "59839d2dc405bc411540a11e",
"question_number": "Q2",
"question_text": "Test question",
"type": "check"
}
]
},
"message": "successful",
"status": "success"
}
You can loop through form inputs based on the server input and display them dynamically like this (working example here).
HTML
<!-- click a button to see a form -->
<button data-ng-click="getQuestions('qs1')">Form 1</button>
<button data-ng-click="getQuestions('qs2')">Form 2</button>
<button data-ng-click="getQuestions('qs3')">Form 3</button>
<form action="">
<input data-ng-repeat="item in questions" type={{item.type}}>
</form>
Controller
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.questions = [];
$scope.getQuestions = function (category) {
//make service call based on category and return questions
//$scope.questions = result of service
//stubbed for example:
$scope.questions = [
{
"answers": [
"Answer 1",
"Answer 2",
"Answer 3"
],
"id": "59839d20c405bc411540a11d",
"question_number": "Q1",
"question_text": "Test question",
"type": "radio"
},
{
"answers": [
"Answer 1",
"Answer 2",
"Answer 3"
],
"id": "59839d2dc405bc411540a11e",
"question_number": "Q2",
"question_text": "Test question",
"type": "checkbox" //this was check, needed to be checkbox - either update service or manipulate it on your end
}
];
};
}]);
Doing just this shows the concept of displaying the inputs dynamically, while only writing one input field. You add more to it, if the service sends it. If you're going to be handling multiple input types, I recommend making a simple dynamic input directive to handle all of this logic, and then simple pass the type into the directive. I have a working example here, but that's the concept. I can help you with that logic as well.