Creating a Simple Custom Directive in AngularJS

Loading

A custom directive in AngularJS allows you to create reusable UI components. Below is a step-by-step guide to creating a simple custom directive.


Step 1: Setup AngularJS

Create an HTML file and include AngularJS.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Custom Directive</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="MainController">
<!-- Using the Custom Directive -->
<hello-world></hello-world>
</div>

<script>
// Step 2: Create an AngularJS Module
var app = angular.module("myApp", []);

// Step 3: Create a Controller
app.controller("MainController", function ($scope) {
$scope.message = "Hello from Controller!";
});

// Step 4: Create a Custom Directive
app.directive("helloWorld", function () {
return {
restrict: "E", // E means it will be used as an element
template: "<h1>Hello, this is a custom directive!</h1>"
};
});
</script>

</body>
</html>

Step-by-Step Explanation

1. Include AngularJS

The script tag includes the AngularJS library in the HTML file.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

2. Define an AngularJS Module

Create an AngularJS application module named "myApp".

var app = angular.module("myApp", []);

3. Create a Controller (Optional)

Define a controller named "MainController" that manages application data.

app.controller("MainController", function ($scope) {
$scope.message = "Hello from Controller!";
});

4. Create a Custom Directive

Use app.directive() to define a custom directive named "helloWorld".

app.directive("helloWorld", function () {
return {
restrict: "E", // 'E' means it's used as an element
template: "<h1>Hello, this is a custom directive!</h1>"
};
});

5. Use the Directive in HTML

Add <hello-world></hello-world> inside the <body> to display the directive content.


Expected Output

When you open this file in a browser, you will see:

Hello, this is a custom directive!

Leave a Reply

Your email address will not be published. Required fields are marked *