Saturday 7 February 2015

Embedding html page using custom directive in AngularJS

We are accustomed using route config for multiple page views in AngularJS. So how about embedding multiple page using custom directive like element, attribute and class directive. Although we can use old method like innerHTML or innerText in jquery, but that is still a huge amount of coding and become more complex when you add more pages, but with angularjs custom directive it's became simpler. Just watch the video and see what you can do with it.

You can download the code from google drive it is in zipped format.

https://drive.google.com/file/d/0BznrW3lgX0ozWWV5ZXUwY2hvRms/view?usp=sharing



1. app.js

var app=angular.module('app',[]);
app.controller('MainCtrl',function($scope) {
 
})
.directive('page1',function() {
  return {
    restrict : 'E',
    templateUrl : 'firstPage.html',
    controller:'MainCtrl'
  }
})
.directive('page2',function() {
  return {
    restrict : 'A',
    templateUrl : 'secondPage.html',
    controller:'MainCtrl'
  }
})
.directive('page3',function() {
  return {
    restrict : 'C',
    templateUrl : 'thirdPage.html',
    controller:'MainCtrl'
  }
});


2. index.html


<html ng-app="app">
    <head>
        <script src="angular.min.js"></script>
        <script src="app.js"></script>       
    </head>
    <body ng-controller="MainCtrl">
        <table border="1">
            <tr>
                <th>Element</th><th>Attribute</th><th>Class</th>
            </tr>
            <tr>
            <td><page1></page1></td>
            <td page2></td>
            <td class="page3"></td>
            </tr>
        </table>
    </body>
</html>


3. firstPage.html

<h2 style="color:red">I am an element and in the first cell
</h2>

4. secondPage.html


<h2 style="color:blue">I am an attribute and in the second cell</h2>

5. thirdPage.html

<h2 style="color:green">I am a class in the last cell</h2>

AngularJS Plunker
ElementAttributeClass

No comments: