2

I have multiple child ng-form which are part of parent ng-form, I want to set the $submitted status of all the child forms, when I set the parent ng-form to $submitted status.

As of now no such method is available on the form-controller, checked here

Lets say, if I want to extend the current form controller to do this, how should I do that? how do I add a new method $setChildFormsToSubmittedState() ? of course I want to do it without disturbing/touching the angular code.

Is it possible? I think it should be given all the child forms hook into parent form using $addControl();.

No idea from where to start.

1
  • make a directive,and attach listener there for parent form submission.. Commented Jan 3, 2015 at 5:23

1 Answer 1

4

You can create a directive that appends a functionality to the form controller. Simply create a method that iterates over all the controls by checking if an item has a $$parentForm property that is equal to the form object it belongs to.

DEMO

Javascript

  .directive('myForm', function() {

    return {
      require: 'form',
      link: function(scope, elem, attr, form) {
        form.__setSubmitted = function() {
          setSubmitted(form);
        };

        function setSubmitted(form) {
          form.$submitted = true;
          angular.forEach(form, function(item) {
            if(item && item.$$parentForm === form) {
              setSubmitted(item);
            }
          });
        }
      }
    };

  });

HTML

<form name="myForm" my-form ng-submit="myForm.__setSubmitted()">
  <ng-form name="mySubForm1">
    <input type="text" ng-model="data.something1" name="something">
    {{mySubForm1.$submitted}}
  </ng-form>
  <br>

  <ng-form name="mySubForm2">
    <input type="text" ng-model="data.something2" name="something">
    {{mySubForm2.$submitted}}
  </ng-form>
  <br>

  <button type="submit">Button</button>
  {{myForm.$submitted}}
</form>
Sign up to request clarification or add additional context in comments.

4 Comments

it works, just one query. why angular.forEach(form,. form is an object, then why do we need forEach on it?
The AngularJS docuemntation states: angular.forEach, Invokes the iterator function once for each item in obj collection, which can be either an object or an array.
ok, so you mean, the form can sometime be collection, hence we need forEach.
The form controller is an object that holds a collection of controls and ngModels.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.