1

Forms in AngularJS sometimes can become a bit ugly. That's my case. I have seemingly simple structure of three forms. Two of them should be related to each other, while third should be completely separate.

<form name="foo">
   <div ng-repeat="f in foo.list">
      <custom-component ng-form="foo['f_'+$index+'_something']"></custom-component>
   </div>
</form>

Above is main form. It binds some part of itself to custom component.

The component on the other hand has two forms inside:

<div ng-form="$ctrl.form">
   <!--foo-->
</div>
<some-popup>
   <div ng-form="$ctrl.popupForm">
      <!--foo-->
   </div >
</some-popup>

The problem is that popupForm is somehow automatically bound with other forms. The result is far from expectations. When I modify popupForm it makes item on foo form dirty. Moreover if some field on popupForm doesn't meet validation criteria, and popup is closed then error is propagated to the foo form's item. The latest problem can be solved with ng-if directive used to "remove" popupFormfrom DOM when popup is hidden, but it still not complete solution.

It there any way to make a form (popupForm of the example) completely separate from other? Can I prevent nesting forms somehow?

Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108

3 Answers3

1

The $removeControl method can be used to remove a child form from its parent.

$removeControl(control);

Deregister a control from the form.

Input elements using ngModelController do this automatically when they are destroyed.

— AngularJS Form Controller API Reference ($removeControl)

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
1

Problem is more complicated. As was mentioned before HTML standard doesn't allow <form> nesting - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form - Permitted content.

If you are not plan to cross-validate this <div ng-form="$ctrl.popupForm"> with <div ng-form="$ctrl.form"> usually this should be done by attach/append popup element do different DOM element.

For example angular-ui components Bootstrap Modal https://angular-ui.github.io/bootstrap/ have property called appendTo. This should solve <form> inheritance issue if you are using modals like Bootrstrap or Material Design http://mseemann.io/frontend/2016/10/10/angular-2-mdl-mdl-dialog-advanced-configuration.html .

More hacky alternatives involve creating custom directive and attach element using https://docs.angularjs.org/api/ng/service/$compile compile functions. Angular directives - when and how to use compile, controller, pre-link and post-link

If you plan to have cross-validation, this should be solved with service/provider for communication and testability.

Community
  • 1
  • 1
Rafał Warzycha
  • 561
  • 3
  • 18
0

Standard HTML doesn't allow nesting forms. Have a look at ngForm.

Giovani Vercauteren
  • 1,898
  • 13
  • 22