Best way to create a list with different inputs


#1

Hi,

I’m working with Ionic for the first time and so far it is pretty amazing. But now I’m not sure how to implement one specific feature of my app:

Requirement: The user should be able to answer a list of dynamically generated questions in the same view. Each question has a specific type (eg. number, text, slider, singlechoice) and at the form will be submitted via a button at the end of the list.

What is the best/Ionic way to create a list like this? Based on the stuff that I found so far I’m leaning towards a custom directive with different templates that is bound to a ng-model.

Thanks in advance!


#2

That’s very possible, if you want a more simple route you could use angular’s ng-show attribute and based upon the condition in that it will show/hide an element. I haven’t done it with Ionic, but in another angular project that I run there are dynamic variables that are set in a database, then in the UI after I pull those, I do ng-repeat on it and it’s all referenced correctly using the repeat variables.

Just gotta get creative!


#3

Like @NorthMcCormick said, you can use ng-if/ng-show to do this. You could also use ng-switch on the type, and when the type is text you will show a text box, when it’s a number show input type=number, etc. Something like this:

<div ng-switch on="data.type">
  <div ng-switch-when="text">
    <input type="text">
  </div>

  <div ng-switch-when="number">
    <input type="number">
  </div>
</div>

If you give us some example code or the structure of your data, we could respond more tailored to your use.


#4

We use this too! Some of the variables are of different types, I even have a JSON object in the database that tells it how to render out a select box and what data to bind to. Angular is so flexible in this way, it’s really an amazing tool. I would share my code if it was readable but it’s fairly complex and tied into my system so it wouldn’t do much good stand alone.


#5
<div ng-repeat="formEle in vm.que">
    <div ng-if="formEle.dataType.toLowerCase() == 'radio'">
        <ion-radio ng-value="'personal'" ng-model="userData[$index]" required>Personal</ion-radio>
    </div>
    <div ng-if="formEle.dataType.toLowerCase() != 'radio'">
        <label class="item item-input item-stacked-label">
            <span class="input-label">{{formEle.question}}</span>
            <input type="{{formEle.dataType.toLowerCase()}}" ng-model="userData[$index]" required>
        </label>
    </div>
</div>

Our server returns either radio, text, email, number. So this does the job for me. But @brandyshea’s example looks good and more readable. Even I am switching to ng-switch now.


#6

Thanks for the feedback! I will try to implement it via ng-switch which is way easier than writing a directive :wink: