Monday 6 June 2016

Render the child elements present inside the Directive element in Angular Js in HTML5

In this post we are going to see how to add the child element in the directive render , normally we have seen that the directive renders the UI or replace the element what we had specified in the directive at the same time you have notice that elements present inside the directive are gone,so now we are going to see how to render the child elements in directive rendering.

In this example we are taken a Directive which is consider as container and contains some UI

var tranApp = angular.module('tranApp',[]);

tranApp.controller('tranController', function ($scope) {

});

tranApp.directive('rootContainer', function () {
   return{
       restrict:'E',
       template:'<div class="panel"><p>This is a sample text</p></div>'
   }
});

So now we see the HTML

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body data-ng-app="tranApp">

<div ng-controller="tranController">

    <root-container>
        <div class="btn btn-info">sample</div>
    </root-container>

</div>

<script type="application/javascript" src="js/jquery-2.0.0.min.js"></script>
<script type="application/javascript" src="js/bootstrap.min.js"></script>
<script type="application/javascript" src="js/angular.min.js"></script>
<script type="application/javascript" src="ang/trans.js"></script>

</body>
</html>

Output:
************


From the code It clears sees an directive named root-container renders the output as above image, but were is the content present inside the directive i.e button, to render this we have to mention transclude to true and have to specify a directive name ng-transclude in some of the element inside the template now angular will append the child elements inside that elements while render like below


tranApp.directive('rootContainer', function () {
   return{
       restrict:'E',
       transclude:true,
       template:'<div class="panel"><p>This is a sample text</p><div ng-transclude=""></div></div>'
   }
});


Output:
***********



From this post you can learn how to add the child elements in the directive rendering in angular js.

No comments:

Post a Comment