Creating dynamic forms using AngularJS directives

Loading

AngularJS is a powerful JavaScript framework that provides developers with a robust way to build dynamic web applications. One of its standout features is directives, which allow developers to extend HTML with reusable components. In this guide, we will explore how to create dynamic forms using AngularJS directives, ensuring flexibility and scalability.

Step 1: Understanding AngularJS Directives

Before we dive into building dynamic forms, it’s important to understand directives in AngularJS. Directives are markers on DOM elements (such as attributes, elements, or comments) that tell AngularJS how to manipulate the DOM. Some built-in directives include:

  • ng-model – Binds form inputs to the scope.
  • ng-repeat – Repeats an HTML element for each item in a collection.
  • ng-if – Conditionally includes an element.
  • ng-show/ng-hide – Shows or hides elements based on a condition.

For dynamic forms, we will create a custom directive that generates form fields dynamically.


Step 2: Setting Up an AngularJS Application

First, let’s create an AngularJS application and include the required script. Below is a basic HTML template that initializes the AngularJS app.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Form with AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="dynamicFormApp">
<div ng-controller="FormController">
<dynamic-form form-data="formFields"></dynamic-form>
</div>
</body>
</html>

In this setup:

  • We define an AngularJS app (dynamicFormApp).
  • We create a controller (FormController) to hold form configurations.
  • We use a custom directive <dynamic-form> to generate form fields dynamically.

Step 3: Creating the AngularJS Module and Controller

We need to define our AngularJS module (dynamicFormApp) and the controller (FormController).

var app = angular.module("dynamicFormApp", []);

app.controller("FormController", function($scope) {
$scope.formFields = [
{ label: "Full Name", type: "text", model: "fullName", required: true },
{ label: "Email", type: "email", model: "email", required: true },
{ label: "Age", type: "number", model: "age", required: false },
{ label: "Gender", type: "radio", model: "gender", options: ["Male", "Female"], required: true },
{ label: "Skills", type: "checkbox", model: "skills", options: ["HTML", "CSS", "JavaScript"], required: false }
];
});

Here’s what we’re doing:

  1. Creating an array of form fields in $scope.formFields.
  2. Each field contains:
    • label: The field label
    • type: Type of input (text, email, number, radio, checkbox)
    • model: The property name that will bind to the user input
    • options: For radio and checkbox fields
    • required: Defines if a field is mandatory

Step 4: Creating a Custom Directive for the Dynamic Form

Now, let’s create the custom directive that will generate form elements dynamically.

app.directive("dynamicForm", function() {
return {
restrict: "E",
scope: {
formData: "="
},
template: `
<form name="dynamicForm">
<div ng-repeat="field in formData">
<label>{{ field.label }}</label>

<!-- Text, Email, Number Fields -->
<input ng-if="field.type === 'text' || field.type === 'email' || field.type === 'number'"
type="{{ field.type }}"
ng-model="formValues[field.model]"
ng-required="field.required">

<!-- Radio Buttons -->
<div ng-if="field.type === 'radio'">
<label ng-repeat="option in field.options">
<input type="radio" ng-model="formValues[field.model]" ng-value="option" ng-required="field.required"> {{ option }}
</label>
</div>

<!-- Checkboxes -->
<div ng-if="field.type === 'checkbox'">
<label ng-repeat="option in field.options">
<input type="checkbox" ng-model="formValues[field.model][option]" ng-required="field.required"> {{ option }}
</label>
</div>

<br>
</div>
<button type="submit" ng-click="submitForm()">Submit</button>
</form>
`,
controller: function($scope) {
$scope.formValues = {};

$scope.submitForm = function() {
console.log("Submitted Form Data:", $scope.formValues);
alert("Form Submitted! Check console for data.");
};
}
};
});

How This Works

  1. The directive is restricted to an element (E), meaning it is used as <dynamic-form>.
  2. The scope has formData, which binds the array of fields from the controller.
  3. The template dynamically generates:
    • input fields for text, email, and numbers.
    • radio buttons for gender selection.
    • checkboxes for skills.
  4. The controller inside the directive:
    • Stores user input in formValues.
    • Logs the form data when the form is submitted.

Step 5: Testing and Running the Application

Now, open the HTML file in a browser and fill in the form. Click submit, and the form data will be logged in the console.

Example output when the form is submitted:

{
"fullName": "John Doe",
"email": "john.doe@example.com",
"age": 25,
"gender": "Male",
"skills": {
"HTML": true,
"CSS": false,
"JavaScript": true
}
}

Step 6: Enhancing the Form

To improve the user experience, we can:

  • Add CSS styles for better form layout.
  • Implement validation messages to alert users about required fields.
  • Use ng-messages for real-time feedback.

Example of adding validation messages:

<p ng-show="dynamicForm.fullName.$error.required">Full Name is required.</p>

Leave a Reply

Your email address will not be published. Required fields are marked *