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.

harishr
  • 17,807
  • 9
  • 78
  • 125

1 Answers1

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>
ryeballar
  • 29,658
  • 10
  • 65
  • 74
  • it works, just one query. why `angular.forEach(form,`. form is an object, then why do we need forEach on it? – harishr Jan 03 '15 at 07:20
  • The [**AngularJS docuemntation states**](https://docs.angularjs.org/api/ng/function/angular.forEach): `angular.forEach`, Invokes the iterator function once for each item in obj collection, which can be either an object or an array. – ryeballar Jan 03 '15 at 07:24
  • ok, so you mean, the `form` can sometime be collection, hence we need forEach. – harishr Jan 03 '15 at 07:35
  • 1
    The `form` controller is an object that holds a collection of `controls` and `ngModels`. – ryeballar Jan 03 '15 at 07:41