How to create a custom directive to append some html code

Say i want to maintain header and footer parts of the body as directives where my html code should not be maintained in index.html instead created a separate header.js and footer.js.

Eg: <header>

<ul><li> Home </li>

<li> Contact </li>

<li> About Us </li>


This i have to maintain in header.js and call up with a directive(element/attribute) like my-header.

Now initially i have to add the script in index.html as follows

<script src=”/directives/custom-directives/my-header.js”></script>

Now again add a custom element in index.html as mentioned below


Lets move on to my-header.js file to create a directive in it..

(function () {
“use strict”;

angular.module(‘myApp’) // ng-app name
.directive(‘myHeader’, function() { // my-header directive creation

return {

“<ul >”+
“<li>About Us</li>”+

either the above way like mentioning in template you can create a directive else you can create a element in controller and append that to index.html as i do below..

link : function($scope, element, attrs,controller) {

var header = angular.element(“<header>”+
“<ul >”+
“<li>About Us</li>”+


You can follow either way in creating a directive..its pretty simple right 😉



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s