The ngForm directive of AngularJS

AD, please don't block.

I go back to talk about form validation in an AngularJS application.

Lately, I had to work with a form created dynamically on the basis of a JSON response, that I get from the server. In this case the approach is a bit different from the one I discussed in my first post about form validation with AngularJS.

So what I had was something like (in the following code for the sake of briefness, I will consider a simplified scenario where the form consists of only input fields of type text):

<form name='sf' ng-controller='FormController' novalidate>
  <div ng-repeat='f in fields'>
    <input name='{{ }}' ng-required='f.isRequired'/>
    <div ng-show='sf[].$dirty && sf[].$invalid'>
      <span ng-show='sf[].$error.required'>Required field</span>

Where fields is defined in the controller. Again, here for the sake of simplicity, I hard-coded the content of the fields variable.

function FormController(scope) {
  scope.fields = [
    { name: 'username', isRequired: true},
    { name: 'password', isRequired: true },
    { name: 'email', isRequired: false}
FormController.$inject = ['$scope'];

But sadly the validation didn’t work.

The reason of this failure, is that currently it’s not possible to dynamically generate a name of an input.

To work around this issue there are two different alternatives: write a custom directive or to trust in the ngForm directive, to create an inner form; I chose this last one:

<form name='sf' ng-controller='FormController' novalidate>
  <div ng-repeat='f in fields'>
    <ng-form name='sfIn'>
      <input name='tb' ng-required='f.isRequired'/>
      <div ng-show='sfIn.tb.$dirty && sfIn.tb.$invalid'>
        <span ng-show='sfIn.tb.$error.required'>Required</span>