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

$parsers and $formatters in Angularjs

$parsers and $formatters are array of function defined on ngModelController . When there is change in values (view or model), the value is passed through the $parsers or $formatters pipeline to convert it according to the needs. $parsers (View to Model): $parsers is an array of function which executes when there is change in view  value ( $veiwValue ), usually via user input. $parsers cause the conversion of view value into the form desirable to assign in model value. The value is passed through each $parsers function and the return value of one function is passed to next function. Last return value is passed to $validators and after validation the value is assigned to model. These $parsers functions are called array order (i.e. index 0 to n). $parsers are not called when there is change in model value programmatically. $parsers function must return some value. If it not, causes parse error and model value is set to undefined . Let's see the simple ...

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=...

Dive into ngIf directive and ngShow directive with example

ngIf and ngShow directives are used very frequently in Angular apps. Here will the difference between these two through an example. Firstly, let's see the main difference between these two as in angular docs: ngIf differs from ngShow and ngHide in that ngIf completely removes and recreates the element in the DOM rather then changing its visibility via display css property. The main points are as follows: ngShow directive uses css display property to show and hide the element in DOM. It does't remove the element from the DOM. It just set class="ng-hide" to hide the element and removes the ng-hide class to show the element. ngIf directive remove and reinsert the element based on the expression provided in ng-if directive. The inserted element has the state which was initialized at the time of compilation. If we change any css property of the element or set any class, that css property and class will be lost if the ng-if expression becomes false and...