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.

Angularjs-custom-directive.html

<html>
   <head>
      <title>JCG tutorial</title>
   </head>
   <body>
      <h1>AngularJS Custom Directives</h1>
      <div ng-app = "myApp" ng-controller = "empCtrl">
         <myemployee name = "Abc"></myemployee>
         <br/>
         <myemployee name = "Xyz"></myemployee>
      </div>
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
      <script>
		var myApp = angular.module("myApp", []);
		myApp.directive('myemployee', function() {
			var directive = {};
			directive.restrict = 'E';
			directive.template = "myemployee: <b>{{myemployee.name}}</b> , Id: <b>{{myemployee.id}}</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>" + $scope.myemployee.name + "</b> , Id: <b>" + $scope.myemployee.id + "</b>, Designation: <b>" + $scope.myemployee.designation + "</b><br/>");
				}
				return linkFunction;
			}
			return directive;
		});
		
		myApp.controller('empCtrl', function($scope) {
			$scope.Abc = {};
			$scope.Abc.name = "Abc";
			$scope.Abc.id = 101;
			$scope.Abc.designation = "Software engineer";
			$scope.Xyz = {};
			$scope.Xyz.name = "Xyz";
			$scope.Xyz.id = 102;
			$scope.Xyz.designation = "Software engineer";
		});         
      </script>
   </body>
</html>

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.

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