Skip to main content

Dynamically Generating Form Elements Using Angularjs

While creating a UI for the web apps, we come up with the situation where we want to get the same type of information from the user. In some situation, we have no idea about the number of that particular type of information the user wanted to provide.

In this situation, we come with the solution to dynamically add the field or group of fields based on the user interaction with the form element. For e.g.: user's phone number- User will decide the number of phones it wishes to enter into the form.

The idea is simple. We will provide the user a way to add the number of fields it requires. There is also a possibility when the user wishes to remove the previously added fields.

To implement the dynamic fields addition, we will use ng-repeat directive to render the fields or group of fields. This ng-repeat directive is to be defined on the div element which wraps the markup for the fields which is to be dynamically added. Let jumps into the code. For the awesome look we will use twitter bootstrap and for the sake of simplicity, we will not implement the validation and submission of the form.

HTML Code:

<form class="form-horizontal" name="personForm">
   <div class="form-group">
     <label for="person_name" class="col-sm-2 control-label">Name:</label>
     <div class="col-sm-7">
       <input type="text" id="person_name" class="form-control" name="person_name" ng-model="person.person_name">
     </div>
   </div>
   <div ng-repeat="o in person.phone">
     <div class="form-group">
       <label for="phone_type" class="col-sm-2 control-label">Phone {{$index+1}}:</label>
       <div class="col-sm-2">
         <select ng-model="o.phone_type" name="phone_type" class="form-control" id="select1" ng-options="t for t in phone_type">
         </select>
       </div>
       <div class="col-sm-5">
         <input ng-model="o.phone_number" type="text" class="form-control" ng-model="o.phone_number">
       </div>
       <div class="col-sm-2">
         <button class="btn btn-danger btn-sm" ng-click="removeFields($index, person.phone)" 
             ng-if="person.phone.length !== 1">-</button>
         <button class="btn btn-primary btn-sm" ng-click="addFields($index, person.phone)">+</button>
       </div>
   </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="reset" class="btn btn-default">Reset</button>
      <button type="submit" class="btn btn-primary">Save</button>
    </div>
  </div>
</form>
Javascript Code:

var app = angular.module('myApp',[]);
app.controller('myAppCtrl',['$scope',function($scope){
 $scope.phone_type = ['Home', 'Office', 'Fax', 'Other'];
 $scope.person = {};
 $scope.person.phone = [ {} ];

 $scope.addFields = function(index, arr){
  arr.splice( index+1, 0, {} );
 };

 $scope.removeFields = function(index,arr){
  arr.splice( index, 1 );
 };
}]);
As you can see that we have created a form which takes the name and multiple phone numbers and its type from the user. The markup the for the elements which is to be multiplied is wrapped into the div having ng-repeat directive. The plus (+) and minus (-) buttons are to be used to add and remove the fields respectively.

As you can see the javascript code on line number 5 where we initialized an array having an empty object so that it can be used by ng-repeat, to generate at least one field for the phone number.

When the user adds or remove the field by clicking plus or minus buttons respectively, ng-click directive will call the addFields() and removeFields() passing where (i.e. $scope.phone) and which (i.e. index) position the new data will be added or removed.

Lastly, we have used ng-if directive to show or hide the minus (-) button based on the condition so that the $scope.phones array must have at least one element. The minus button will not show if $scope.phones has only one element.

Working Examples:



Comments

Popular posts from this blog

Automatic Slashing the Date Input using Angularjs

We define a directive that will automatically slash the input field as user typein the date. The directive have following capabiltiy: The directive will append slash '/' when input field has 2 or 5 characters. The input will accept only 10 characters (dd/mm/yyyy). Validity of date provide will not be checked. When the backspace is pressed it will remove the last two character if last character is slash. Otherwise it will remove last character from the input field. The input will not accept characters other than numbers (0 to 9). Let's jump into the code. We will use bootstrap for awesome look: HTML Code: <div class="container" ng-app="myApp" ng-controller="myAppCtrl"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <form class="form-horizontal"> <h4 class="bg-primary">Auto Slashing Date using Angularjs Directive</h4> <div class=...

Code Syntax Highlighting on Blogger using Prismjs

Prismjs is developed by Lea Verou. It is a lightweight, extensible syntax highlighter, built with modern web standards in mind. It’s used in thousands of websites, including some of those you visit daily.Today, we will see how to use the prismjs on blogger to highlight our codes. It very easy and step by step process to follow: Goto to this link and get the personalized links for prismjs or simply copy the links given below: <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/themes/prism-coy.min.css" rel="stylesheet"></link> <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.0/prism.min.js"></script> Goto Theme > Edit HTML and paste the links before the closing </head> section as shown below: Default prism.min.js file contain the functionality to highlight the code for only HTML, CSS and JS code. If you wish to use other language to highlight, you have to paste the link for that langu...

Conversion between Date String and Timestamp using Angularjs Directive

Let me ask you one question. Can a veiwValue and modelValue have same value into a different format? The answer is YES . Here we will see how it can be possible. We will see it through a simple example that converts date string (viewValue) into timestamp (modelValue). We will use a text box to enter a date string (dd/mm/yyyy) and convert it into timestamp that will be stored into model value. The trick is that we will use $parsers to convert the date string into the timestamp and $formatters to change the timestamp stored in modelValue to date string that will be shown on text input. Let's see the codes first: HTML Code: <h4>Date to Timestamp</h4> <div class="form-group"> <label for="date1" class="col-sm-3 control-label">Date1 VeiwValue:</label> <div class="col-sm-3"> <input type="text" id="date1" class="form-control" name="date1" ng-model="ob...