Search code examples
angularjsangularjs-ng-repeatng-submit

build a form using multiple ng repeats how to proccess the data? angular js


Im building a cart. Each product has "addons" these for example

  • size:big
  • dressing: No salad dressing
  • Drink: cola

these "addons" are from the database. and returned from the API as objects.

object looks like this: object cat_addons (addon_group) -object (addon) -object - etc object item addons (addon_group) -object (addon) -object - etc

now im making the "form" wich shows the select boxes and stuff and a "add" button. Now when the user clicks OK/add i want all selected values so i can further process it... but now i have no clue anymore to to this, because the ng-model has to be variable because its created in a repeat.

so im searching for a option to get all selected values form a (multi) ng-repeat populated form how can i do that?

view:

<form ng-submit="addItemToCart()">
    <!-- ADDONS -->
    <!-- CAT ADDONS -->
    <div ng-if="cat_addons">
        <div ng-repeat="(k, addon_group) in cat_addons">
            {{addon_group.addon_group_name}}
            <!-- SINGLE OPTION-->
            <div ng-if="addon_group.addon_option_type == 'single'">
            <span>
                <select ng-options="addon.addon_name as addon.addon_id for addon in addon_group.items">
                    <!-- SHOWS NOTHING? -->
                </select>
            </span>
            </div>
            <!-- SINGLE OPTION -->

            <!-- MULTI OPTION-->
            <div ng-if="addon_group.addon_option_type == 'multi'">
            <span ng-repeat="(k, addons) in addon_group.items">
                <input type="checkbox" name="{{addons.addon_id}}">{{addons.addon_name}}
            </span>
            </div>
            <!-- MULTI OPTION -->
        </div>
    </div>
    <!-- CAT ADDONS -->
    <!-- ADDONS -->
    <button type="submit">ok</button>
</form>

controller:

        $scope.addItemToCart = function() {
            //i have no clue...
        }

Solution

  • I understand the urge to use ng-repeat once you discover what it's capable of. But there is a lot more to angular that makes things such as this issue much simpler. You might want to explore ngOptions directive (https://docs.angularjs.org/api/ng/directive/ngOptions) or the select tag (https://docs.angularjs.org/api/ng/directive/select).

    If these are not what you're looking for, try and go through the documentation to explore angular. I'm sure you will enjoy it. If you are still stuck, comment on this answer and I'll help you out. I do know how to implement what you want using ng-repeat but it is not even close to the best way to do what you want to.