0

I have an older project in Ionic v1 (Angular 1.x) where users can create groups and add members. I need to add a capability to the App for the group Admin to ask questions to group members - sort of a dynamic form. The questions can be of three types - a Yes/No (to be shown as a toggle), String (input Text) and a question with choices (to be shown as a select drop down). The number of questions can vary.

The questions are stored along the lines of the hash below.

{
        id1: {q: "question1", type: "String"},
        id2: {q: "question2", type: "Yes/No"}
        id3: {q: "question3", type: "Choice", choices: "Choice1, Choice2, Choice3"},
        id4: {q: "question4", type: "String"},
        id5: {q: "question5", type: "Yes/No"}
        id6: {q: "question6", type: "Choice", choices: "Choice4, Choice5, Choice6"}
}

I am trying to think of the best way to be able to show these questions dynamically to the user and collect the answers but not quite sure what's the best way to do this. I started looking at trying to create a Directive but wanted to get advice before spending too much time down a path.

Look forward to your thoughts and suggestions.

-S

  • Please check https://stackoverflow.com/questions/12044277/how-to-validate-inputs-dynamically-created-using-ng-repeat-ng-show-angular/32907176?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Manoj Bhardwaj Apr 05 '18 at 03:48

1 Answers1

0

I would suggest a simpler approach than using a directive, unless you have the need to reuse this as a component across multiple views. Start by having ng-repeat="(key, value) in questions" where questions is the name of your object. Then simply show/hide different forms for each question based on value.type: ng-if="value.type=='String'"...

The form you show in each case would be a checkbox for yes/no, textarea or input(type=text) for string and radio buttons for choice.

I'm not providing full code as I assume you know enough Angular to be able to create those - if not each case is an easy google away. One further thing you'll need is a place on each question for the model (i.e., the user's answer), which might be value.answer. For example:

<input type="checkbox" ng-model="value.answer">

Does this make sense?

see sharper
  • 11,505
  • 8
  • 46
  • 65