By kswaughs | Monday, June 13, 2016

AngularJS Directive with arguments

An AngularJS Directive is an extension of HTML with new attributes.

AngularJS provides many built-in directives that offers functionality to our applications like ng-app, ng-repeat.

AngularJS also let us create our own directives. These new directives are created by using .directive function

Use Case

Below Example shows that a custom directive is used to print the list of blog posts available in where the label of the blog post is passed as an attribute of that directive element in the HTML code.

This directive first displays the label that is passed and allows an on click event and calls a rest service to get available blog posts.

HTML & AngularJS code
<!doctype html>
<link href="styles.css" rel="stylesheet" type="text/css">
<script src=""></script>
    var app = angular.module('DirectiveExample', []);
    app.directive('blogPostSummary', function() {
        return {
            template: '<div class="ajtitle" ng-click="getBlogPosts()">'+
                      'Posts of {{label}}'+
                      '</div>' +
                      '<ul class="list">'+
                      '<li ng-repeat="entry in myData" >'+
                      '<a class="entry"'+
                      'ng-repeat="link in | filter:{rel: \'alternate\'}"' +
            scope: {
                label: '@'
            link: function(scope, elem, attrs) {
            controller : function($scope, $http) {

                $scope.getBlogPosts = function() {

                    $scope.label + "?alt=json")
                    .then( function(response) {
                        $scope.myData =;
    <div ng-app="DirectiveExample">
        <blog-post-summary label="AngularJS"></blog-post-summary>
        <blog-post-summary label="Camel"></blog-post-summary>
        <blog-post-summary label="Junit"></blog-post-summary>

.ajtitle { 
padding:10px 0px 10px 15px;
width : 550px;
font-weight : bold;
border-top:1px solid #fafafa;
border-bottom:1px solid #e0e0e0;
background: #ededed;
background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ebebeb));
background: -moz-linear-gradient(top,  #ededed,  #ebebeb);

.entry {
text-decoration: none;
color : blue;

.list {
list-style: none;
width : 500px;

.list li{
 border-bottom:1px solid #e0e0e0;
 padding:10px 0px 10px 0px;

Demo : click on below tabs

Recommend this on