AngularJS Custom Directives Example

Welcome readers, in this tutorial, we will understand custom directives in angularjs.

1. Introduction

1.1 Commonly used Directive properties

In this tutorial, we’ll focus on Element directive as they are most used today.

2. AngularJS Custom Directives Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using the HTML editor to create an HTML file and play it in the browser.

3. Creating a HTML file

Add the following code to the html file.


      <title>JCG tutorial</title>
      <h1>AngularJS Custom Directives</h1>
      <div ng-app = "myApp" ng-controller = "empCtrl">
         <myemployee name = "Abc"></myemployee>
         <myemployee name = "Xyz"></myemployee>
      <script src = ""></script>
		var myApp = angular.module("myApp", []);
		myApp.directive('myemployee', function() {
			var directive = {};
			directive.restrict = 'E';
			directive.template = "myemployee: <b>{{}}</b> , Id: <b>{{}}</b>, Designation: <b>{{myemployee.designation}}</b>";
			directive.scope = {
				myemployee: "=name"
			directive.compile = function(element, attributes) {
				var linkFunction = function($scope, element, attributes) {
					element.html("Employee: <b>" + $ + "</b> , Id: <b>" + $ + "</b>, Designation: <b>" + $scope.myemployee.designation + "</b><br/>");
				return linkFunction;
			return directive;
		myApp.controller('empCtrl', function($scope) {
			$scope.Abc = {};
			$ = "Abc";
			$ = 101;
			$scope.Abc.designation = "Software engineer";
			$scope.Xyz = {};
			$ = "Xyz";
			$ = 102;
			$scope.Xyz.designation = "Software engineer";

And done! We have created a simple HTML page that developers can double click to preview in a browser.

4. Run the Application

Double click on the HTML file to preview in the browser of your preferred choice.

5. Project Demo

If everything goes well, custom directive will display the employee’s information.

Fig. 1: Index page

That is all for this tutorial and I hope the article served you whatever you were expecting. Happy Learning and do not forget to share!

6. Conclusion

In this section, we learned how to create custom directives in an angularjs application. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Angular Project

This was a tutorial of Custom Directives in AngularJS.

You can download the full source code of this example here: AngularJS Custom Directives Example
Exit mobile version