AngularJs Add Form Fields Dynamically


AngularJs Add Form Fields Dynamically- It is very easy to add the form fields dynamically sometimes we need some form fields to add dynamically. Here in this tutorial we are going to explain how you can create functionality to add some dynamic fields. You can also use our online editor to edit and try the code online.


AngularJs Add Form Fields Dynamically

Let us go step by step to create the dynamic form fields-

Html Part

Html part contains the following part-

AngularJs Add Form Fields Dynamically Example:

<div ng-app="myApp">  
<div ng-controller="myController"> 
<h3>Register Form</h3>
<form>
<table>
<tr><td>Name</td><td><input type="text" ></td></tr>
<tr><td>Email</td><td><input type="text" ></td></tr>
<tr ng-repeat="phone in contacts"><td>Phone {{$index+1}}</td><td><input type="text" name="phone-{{phone.id}}" ><button type="button" ng-click='removePhone($index);'>-Remove</button></td></tr>
<tr><td></td><td><button type="button" ng-click='addMorePhone();'>+Add More</button></td></tr>
<tr ng-repeat="edu in qualifications"><td> Qualification {{$index+1}}</td><td><input type="text" name="education-{{edu.id}}" ><button type="button" ng-click='removeQualifications($index);'>-Remove </button></td></tr>
<tr><td></td><td><button type="button" ng-click='addMoreEdu();'>+Add More</button></td></tr>

<tr><td>Submit</td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
 
</div> 
</div>

JavaScript Part

JavaScript Part Contains the following parts –

AngularJs Add Form Fields Dynamically Example:

<script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.contacts = [{'id':1}];
 $scope.counterContacts = 1;
 $scope.counterQalifications = 1;
 $scope.qualifications = [{'id':1}];
 $scope.addMorePhone = function() { 
    $scope.counterContacts++;
	$scope.contacts.push({'id' :$scope.counterContacts});
 };
 $scope.addMoreEdu = function() { 
    $scope.counterQalifications++;
	$scope.qualifications.push({'id' :$scope.counterQalifications});
 };
  $scope.removeQualifications = function(index) { 
    if(index != -1){
	$scope.counterQalifications--;
	$scope.qualifications.splice(index,1);
	}
 };
 $scope.removePhone = function(index) { 
	if(index != -1){
	$scope.counterContacts--;
	$scope.contacts.splice(index,1);
	}
 };
});
</script>

Try it »

If you run the above example it will produce the output something like this –

AngularJs Add Form Fields Dynamically


Advertisements

Add Comment

📖 Read More