salacis
salacis

Reputation: 205

Work with multiple Forms and its values

Assume an certain amount of forms created by ng-repeat, which allows the user to sum something up like a+b and display the result instantly. How would the Controller look like?

<div data-ng-repeat="form in forms">
    <form name={{form.name}}>
        <input type="text" name="a" ng-modal="?">
        <input type="text" name="b" ng-modal="?">
     </form>
     <p>{{?.result}}</p>
</div>

The question marks within the html should be something unique I guess. And the controller may access something like an array of forms from scope ... but maybe someone has a suggestion

Upvotes: 1

Views: 1291

Answers (1)

PzYon
PzYon

Reputation: 2993

If I understand your question correctly and assuming you have defined the forms in an array for example, below code should work for you:

<!DOCTYPE html>
<html data-ng-app="formApp">
    <head>
        <script type="text/javascript" src="https://code.angularjs.org/1.2.26/angular.js"></script>
        <script type="text/javascript"> 
            var formApp = angular.module("formApp",[]);

            formApp.controller("formController", function($scope)
            {
                $scope.forms = [{name: "Foo"}, {name: "Bar"}];
            });
        </script>
    </head>
    <body data-ng-controller="formController">
        <div data-ng-repeat="form in forms">
            <form name={{form.name}}>
                <input type="text" name="a" data-ng-model="form.someField">
                <input type="text" name="b" data-ng-model="form.someOtherField">
             </form>
             <p>{{form.someField + form.someOtherField}}</p>
        </div>
    </div>
</html>

So basically you were right when mentioning "array of forms from scope".

The important thing to know is that angular creates a new scope for every item in the collection when using ng-repeat. This means, you do not need to use unique member names. "form.someField" for example always references the member of the current scope.

The calculation you would like to perform could be done inline as in my example or you could move it to an own method on a "class" from which all items in the form collection will inherit.

By the way: it's "data-ng-model" and not "data-ng-modal" ;)

Upvotes: 1

Related Questions