Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / AngularJs

AngularJs: Add, Remove Directives Dynamically & Save Details

5.00/5 (4 votes)
12 Oct 2015CPOL2 min read 66.6K  
AngularJs: Add, Remove Directives Dynamically & Save Details

Introduction

In this tip, I will explain how to add, remove directives dynamically and save data in Angularjs.

Background

What is directive in AngularJs?

AngularJs allows you to write your own HTML element, attribute, comment, CSS class and also customize the existing HTML element through directives. AngularJS's HTML compiler ($compile) traverses the DOM and matches directives based on element names, attributes, class names and comments and attaches these directives to the DOM element.

Using the Code

1. Create a Directive of Type Element

JavaScript
demo.directive('contactType', function() {
 return {
   restrict: "E",
   scope: {},
   templateUrl:'ContactType.html',   
   controller: function($rootScope, $scope, $element) {
     $scope.contacts = $rootScope.GetContactTypes;     
   }
 }
});

Here is the list of used options in directive...

Image 1

Create file with ContactType.html as below:

XML
<div class="container">
   <div class="form-inline" >
   <div class="form-group" style="margin-right:20px">       
      <select name="ContactType" class="form-control" 
      style="width:200px" ng-model="ContactType"  >
        <option ng-repeat="contact in contacts" 
        value="{{contact.contactId}}">   {{contact.contactType}}   </option>
      </select>
   </div>
   <div class="form-group" style="margin-right:20px">      
      <input type="text" style="width:200px" 
      class="form-control" ng-model="ContactValue" name="contactValue" >
   </div>
    <div class="form-group" style="margin-right:20px">      
   <button ng-click="Delete($event)" class="btn btn-danger">
   <i class="glyphicon glyphicon-trash"></i></button>
   <span ng-model="Status">{{Status}} </span>
   </div>
 </div>
 <br/>
</div>

Image 2

Create a service to populate dropdown list called ContactTypesService which returns list of contact Types:

JavaScript
demo.service("ContactTypesService", [function() {
 var list = [];
 return {
   ContactTypes: function() {
     list.push({contactId: 1,contactType: 'Mobile'});
     list.push({contactId: 2,contactType: 'Office'});
     list.push({contactId: 3,contactType: 'Home'});
     list.push({contactId: 4,contactType: 'Fax'});
     list.push({contactId: 5,contactType: 'Landline'});
     list.push({contactId: 6,contactType: 'Other'});
     return list;
   }
 }
}]);

Create model Employee with property firstName, lastName, contacts and also create view for model Employee with two buttons New Contact and Submit details (Refer Index.html).

Image 3

2. Add Directive Dynamically

$Compile: To add new directive dynamically into DOM, directives need to be compiled.

When user clicks on New Contact button, the below function will get called:

JavaScript
$scope.AddContactTypeControl = function() {
   var divElement = angular.element(document.querySelector('#contactTypeDiv'));
   var appendHtml = $compile('<contact-Type></contact-Type>')($scope);
   divElement.append(appendHtml);
 }
JavaScript
<button class="btn btn-primary" ng-click="AddContactTypeControl()">
<span>New Contact</span>
</button>

The below screen will appear when user clicks New Contact button thrice.

Image 4

3. Delete Directive from DOM

To remove directive from DOM, click the delete image button from added directives, which calls below function. For this, the below code should be added in directives controller. This code contains an important step to destroy directives scope (i.e., $scope.$destroy()).

JavaScript
$scope.Delete = function(e) {
  //remove element and also destroy the scope that element
  $element.remove();
  $scope.$destroy();
}

4. Save Details

Most important step is to save all the details.

Here, we will get value of firstName and lastName through model and to get value of dynamically added directives, we need to get all child scopes of parent scope. For this, we need to iterate child scope and push the values into an array as below:

JavaScript
var retriveValue = function() {
   var UserContacts = [];
   var ChildHeads = [$scope.$$childHead];
   var currentScope;
   while (ChildHeads.length) {
     currentScope = ChildHeads.shift();
     while (currentScope) {
      if (currentScope.ContactType !== undefined)
         UserContacts.push({
           ContactType: GetContactType(currentScope.ContactType),
           ContactValue: currentScope.ContactValue
         });
       currentScope = currentScope.$$nextSibling;
     }
   }
   return UserContacts;
 }

Please find the detailed code in script.js.

After entering and saving the details you can see the data in tabular format as below:

Image 5

Image 6

Complete running code available at plunker at http://plnkr.co/edit/a7E9sT?p=info.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)