AngularJS tips and tricks – nesting form elements

A very small trick indeed, but very important to me. I was having trouble incorporating my AngularJS-application into a .net environment. ASP.net web forms require a form tag to work, and my application had a form already. I was validating this existing form by using AngularJS’s ability to automatically keeping track of the forms valid/invalid state via $scope.mainform.$invalid. This feature in AngularJS uses the name of the form as a reference – but this creates problems in asp.net.

I tried combining the forms, so that the asp.net form tag would work together with my AngularJS-form tag. Something like this:

<form method="post" name="mainform" runat="server" id="mainform" ng-controller="MainCntl">

However, this didn’t work. The reason is that asp.net removes the name part of the form-tag in order to ensure strict XHTML-compliance. So now my form-validation didn’t work any longer.

You can adjust this setting in web.config, so that asp.net will allow legacy or transitional rendering, but you can also just use a neat feature in AngularJS, which allows you to nest forms.

Therefore, you can write this instead:

<form runat="server">
  <ng-form name="mainform" id="mainform" ng-controller="MainCntl">

The ng-form is a special AngularJS form alias allowing you to have multiple forms in your HTML-document. This is described in more detail in the reference: http://docs-angularjs-org-dev.appspot.com/api/ng.directive:form

Maybe a bit of a hack, but it works….

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s