July 04, 2016

How to add ionic or angular directives dynamically on runtime in html

Angular JS facilitates user to dynamically add angular directives or ionic directives or any custom made angular directives in html and update the page accordingly.

To implement it we need to use $compile function which deals with transforming the template DOM.

Format of compile function:

 function compile(tElement,tAttrs,transclude){...}  

The compile function takes the following arguments:
  • tElement - template element - The element where the directive has been declared. It is safe to do template transformation on the element and child elements only.
  • tAttrs - template attributes - Normalized list of attributes declared on this element shared between all directive compile functions.
  • transclude - [DEPRECATED!] A transclude linking function: function(scope, cloneLinkingFn)

Example of using compile function to dynamically add directives:

Lets create an array list and show the list in ion-list directive dynamically. 

JavaScript (app.js) Code:

 var htmlStr = ' <ion-list>'+  
    '<ion-item ng-repeat="item in nlist">'+  
     'Number {{item}} '+  
    '</ion-item>'+  
   '</ion-list>';  
 angular.module('myApp', ['ionic'])  
 .controller('THController', function($scope) {   
  $scope.doRefresh = function() {              
     var $target = $("#ioncontentpane");  
     angular.element($target).injector().invoke(function($compile) {  
       var $scopen = angular.element($target).scope();  
       $target.append($compile(htmlStr)($scope));  
       // Finally, refresh the watch expressions in the new element  
       $scopen.$apply();  
      });  
     $scope.nlist = [1,2,3];  
          $scope.$broadcast('scroll.refreshComplete');  
  };  
 });  

HTML code:

1:  <!DOCTYPE html>  
2:  <html>  
3:   <head>  
4:    <meta charset="utf-8">  
5:    <title>MyApp</title>  
6:    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">  
7:    <link href="css/ionic.css" rel="stylesheet">  
8:    <script src="js/jquery2.2.min.js"></script>  
9:    <script src="js/ionic.bundle.js"></script>  
10:    <script src="js/app.js"></script>  
11:   </head>  
12:   <body ng-app="myApp">  
13:    <ion-pane>  
14:    <ion-header-bar class="bar-stable">  
15:     <h1 class="title">Number List</h1>  
16:    </ion-header-bar>  
17:    <ion-content ng-controller="THController" id="ioncontentpane">  
18:    <ion-refresher  
19:     pulling-text="Pull to refresh..."  
20:     on-refresh="doRefresh()">  
21:    </ion-refresher>  
22:    </ion-content>  
23:   </ion-pane>  
24:   </body>  
25:  </html>  

the above code will display plain page with header, but when we pull down the page, it will dynamically add the items list directive and display the data as well.

Screenshots of output of the example:

Before pull-to-refresh event trigger:


After event trigger:



No comments:

Post a Comment