angularjsionic-frameworkangularjs-ng-repeatangular-ngmodelangularjs-forms

angular checkbox form with ng-repeat can only select one option


I am trying to create a multistep form and step 2 is a bunch of checkboxes. Here is the form with checkboxes:

<form ng-submit="createSubCategory(formData)">
    <div ng-repeat="sub_category in event_sub_categories">
        <ion-checkbox ng-model="formData.sub_category" ng-true-value="'{{sub_category}}'">
          {{sub_category}}</ion-checkbox>
    </div>
    <button type="submit" class="button button-block button-positive">Continue</button>
</form>

The data for the checkboxes (event_sub_categories) is pulled from a server. I need to save the inputs selected by the user to formData. formData is being collected on each page of the multistep form and it will be submitted with a post request after all of the form pages. I am new to angular and I am somewhat confused as to how check boxes work.

Question 1: I understand how ng-model works with normal textfields. But I'm not sure I get how it works with checkboxes. Does ng-model replace the html name element? Meaning, when I submit this to the server using $resource, are the keys of the data set by ng-model?

question 2: How can I name ng-model so that it is part of formData but so that it is also related to the name of sub_category being pulled from the database. The problem is that with the code above, only one checkbox can be selected at any given time and I want the user to be able to check many checkboxes at a given time. If it's not possible to do this, how can I get the functionality I need with checkboxes?


Solution

  • To be able to select multiple checkboxes at once you need an object (angular) to hold all of the values. I have implemented this code in my own applications and find it fairly easy for the function receiving it to interpret the object. (iterate the object checking for true/false values)

    Here is your <ion-checkbox> code:

    <ion-checkbox ng-repeat="sub_category in event_sub_categories" ng-model="formData[sub_category]">
    

    This will set subcategory: true/false inside the formData object for every checkbox that is clicked.

    Then all you need to do is send that formData object to where ever, the same way you were doing as before. Here is a codepen that displays the checkboxes changing, the updated formData object and the formData object stringified.

    http://codepen.io/anon/pen/LNdaev?editors=1010

    I have created my own values for event_sub_categories as an example, so of course these would be different from your own

    Comment if you have any questions.