AngularJS Directives

AngularJS directives are one of its most powerful features, allowing you to extend HTML with custom behavior. They can be used to manipulate the DOM, create reusable components, and implement dynamic features in your application.

In this guide, we’ll explore AngularJS directives, their types, usage, and practical examples to help you build dynamic and interactive applications. For more AngularJS tutorials, visit The Coding College.

What Are AngularJS Directives?

Directives in AngularJS are special markers (attributes, elements, or classes) in the DOM that tell AngularJS to attach specific behaviors or execute custom logic. Essentially, they bridge the gap between the HTML and the application logic.

Example:

<div ng-app="myApp">
    <p ng-bind="message"></p>
</div>

In this example, ng-bind is a directive that binds the message variable to the <p> element.

Types of AngularJS Directives

  1. Built-in Directives: Predefined directives provided by AngularJS (e.g., ng-model, ng-repeat, ng-if).
  2. Custom Directives: User-defined directives to create reusable components or encapsulate functionality.

Commonly Used Built-in Directives

1. ng-app

Defines the root element of an AngularJS application.

<div ng-app="myApp"></div>

2. ng-model

Binds the value of HTML elements to application data.

<input type="text" ng-model="name">
<p>{{ name }}</p>

3. ng-bind

Binds application data to the view.

<p ng-bind="greeting"></p>

4. ng-repeat

Repeats an HTML element for each item in a collection.

<ul>
    <li ng-repeat="item in items">{{ item }}</li>
</ul>

5. ng-if

Conditionally includes or excludes an element based on a Boolean expression.

<p ng-if="isVisible">This is visible!</p>

6. ng-click

Adds click event listeners to elements.

<button ng-click="sayHello()">Click Me</button>

Creating a Custom Directive

Custom directives allow you to define your own behavior and functionality.

Syntax:

app.directive('directiveName', function() {
    return {
        restrict: 'A', // Restriction type (A = Attribute, E = Element, C = Class, M = Comment)
        template: '<h1>Hello, {{ name }}</h1>',
        scope: { name: '@' }, // Isolated scope
        link: function(scope, element, attrs) {
            // DOM manipulation logic here
        }
    };
});

Example: Custom Directive

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp">
        <welcome-message name="AngularJS"></welcome-message>
    </div>

    <script>
        // Define the module
        var app = angular.module('myApp', []);

        // Create a custom directive
        app.directive('welcomeMessage', function() {
            return {
                restrict: 'E', // Restrict to Element
                template: '<h2>Welcome to {{ name }}</h2>',
                scope: {
                    name: '@' // Bind the `name` attribute
                }
            };
        });
    </script>
</body>
</html>

Output:

Welcome to AngularJS

Restriction Types in Directives

  • A (Attribute): Directive is used as an attribute.
  • E (Element): Directive is used as an HTML element.
  • C (Class): Directive is used as a CSS class.
  • M (Comment): Directive is used in comments.

Example:

app.directive('myDirective', function() {
    return {
        restrict: 'AECM', // Allow usage as Attribute, Element, Class, or Comment
        template: '<p>This is a custom directive!</p>'
    };
});

Scope in Directives

Directives can have their own isolated scopes.

Types of Scope Binding

  1. @ (Text Binding): One-way binding for string literals.
  2. = (Two-Way Binding): Allows bidirectional data binding.
  3. & (Function Binding): Binds a method from the parent scope.

Practical Example: Dynamic Tooltip Directive

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp">
        <button tooltip="Click to submit!">Submit</button>
    </div>

    <script>
        var app = angular.module('myApp', []);

        app.directive('tooltip', function() {
            return {
                restrict: 'A',
                link: function(scope, element, attrs) {
                    element.attr('title', attrs.tooltip);
                }
            };
        });
    </script>
</body>
</html>

Output:
Hovering over the “Submit” button displays the tooltip “Click to submit!”

Benefits of Directives

  1. Reusable Components: Encapsulate reusable functionality.
  2. Custom Behavior: Extend HTML with custom features.
  3. Separation of Concerns: Keep logic separate from the HTML view.
  4. Dynamic Content: Easily manage dynamic changes to the DOM.

Conclusion

AngularJS directives empower developers to create rich, interactive, and reusable components in their applications. By combining built-in and custom directives, you can efficiently manage your application’s UI and functionality.

Leave a Comment