Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking a form between multiple tabs in angular breaks validation

I have an angular form spitted between several tabs with angular UI directive.

<form name="campaignForm" class="form-horizontal" novalidate >
<input type="text" name="title" class="input-xxlarge" placeholder="Campaign title" ng-model="campaign.title" required>
  <span ng-show="campaignForm.title.$error.required" class="help-inline">
      Required</span>

<tabset>
<tab>
</tab>
<input type="email" name="emailFrom" class="input-xsmall" placeholder="From email address" ng-model="campaign.info.emailFrom" required="" />
      <span ng-show="campaignForm.emailFrom.$error.required" class="help-inline">
          Required</span>
<tab>
<input type="text" name="emailSubject" class="input-xxlarge" ng-model="campaign.info.emailSubject" placeholder="Please enter email subject" required/>
<span ng-show="campaignForm.emailSubject.$error.required" class="help-inline">
              Required</span>
</tab>
</tabset>
</form>

Please see my Plunker.

As you can see, only the input outside tabs directive works. The other inputs validation doesn't work because TABS create scopes. Any ideas how to solve this issue?

like image 233
Alexandru R Avatar asked Jul 02 '13 08:07

Alexandru R


1 Answers

From the ngForm directive docs:

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of <form> elements, so Angular provides the ngForm directive, which behaves identically to form but can be nested.

This means that you can break your campaignForm form into sub-forms for each tab:

<form name="campaignForm" class="form-horizontal" novalidate >
  <tabset>
    <tab heading="first">
      <div ng-form="emailForm">
        <input type="email" name="emailFrom" class="input-xsmall" placeholder="From email address" ng-model="campaign.info.emailFrom" required />
        <span ng-show="emailForm.emailFrom.$dirty && emailForm.emailFrom.$error.required" class="help-inline">
          Required
        </span>
      </div>
    </tab>

    <tab heading="second">
      <div ng-form="subjectForm">
        <input type="text" name="emailSubject" class="input-xxlarge" ng-model="campaign.info.emailSubject" placeholder="Please enter email subject" required/>
        <span ng-show="subjectForm.emailSubject.$dirty && subjectForm.emailSubject.$error.required" class="help-inline">
          Required
        </span>
      </div>
    </tab>
  </tabset>
</form>

PLUNKER

This will circumvent the case where tabs directive (or any other directive that uses isolate scope) is breaking your ngFormController's scope.

like image 85
Stewie Avatar answered Oct 16 '22 10:10

Stewie