Creating dynamic forms in AngularJS involves using directives, controllers, and data binding to dynamically generate form elements based on certain conditions or data. Here's a basic approach to creating dynamic forms in AngularJS:
html<!DOCTYPE html>
<html lang="en" ng-app="dynamicFormApp">
<head>
<meta charset="UTF-8">
<title>Dynamic Forms in AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="DynamicFormController">
<form ng-submit="submitForm()">
<!-- Dynamic form elements will be generated here -->
<button type="submit">Submit</button>
</form>
</div>
<script src="app.js"></script>
</body>
</html>
javascript// app.js
angular.module('dynamicFormApp', [])
.controller('DynamicFormController', function($scope) {
// Initialize form data
$scope.formData = {};
// Define dynamic form elements
$scope.formElements = [
{type: 'text', label: 'Name', model: 'name'},
{type: 'email', label: 'Email', model: 'email'},
{type: 'password', label: 'Password', model: 'password'}
];
// Function to submit form
$scope.submitForm = function() {
// Handle form submission here
console.log('Form submitted:', $scope.formData);
};
});
ng-repeat
to loop through formElements
array and generate form elements dynamically.html<!-- Inside the form -->
<div ng-repeat="element in formElements">
<label>{{element.label}}:</label>
<input type="{{element.type}}" ng-model="formData[element.model]" />
</div>
This will dynamically generate form fields based on the data in the $scope.formElements
array. When the form is submitted, the data will be available in the $scope.formData
object. You can extend this example to include more complex form elements and validation as needed.