🧠 AngularJS Directives & Pipes
Estimated reading: 4 minutes 24 views

πŸ§ͺ AngularJS Custom Directives (2025 Guide)

🧲 Introduction – Why Learn AngularJS Custom Directives?

While AngularJS offers a wide range of built-in directives, sometimes you need custom behavior or reusable UI components not covered by the framework. That’s where custom directives come in. They allow you to create your own HTML tags or attributes with custom logic, templates, and interactivity.

By learning custom directives, you gain full control over:

  • Reusable components (e.g., modal, tooltip, tabs)
  • DOM manipulation logic
  • Attribute or event behaviors
  • UI enhancements and encapsulation

🎯 In this guide, you’ll learn:

  • What custom directives are in AngularJS
  • How to create and use them
  • Different directive configurations (restrict, scope, template, link)
  • Real-world examples and best practices

πŸ“˜ What Is a Custom Directive?

A custom directive in AngularJS is a reusable functionality that you define using app.directive(). It lets you create your own:

  • HTML elements
  • Attributes
  • Classes or comments with logic attached

πŸ”§ Basic Custom Directive Syntax

app.directive('myDirective', function() {
  return {
    restrict: 'E', // Element name
    template: '<h3>Hello from Custom Directive!</h3>'
  };
});

HTML Usage:

<my-directive></my-directive>

🧾 This directive displays the given template wherever <my-directive> is used.


πŸ” Restrict Options in Directives

ValueDescriptionExample Use
'E'Directive as an HTML Element<my-directive></my-directive>
'A'Directive as an Attribute<div my-directive></div>
'C'Directive as a Class<div class="my-directive"></div>
'M'Directive as a Comment<!-- directive: my-directive -->
'EA'Element and Attribute (Most Common)Element + Attribute Use

βœ… Example – Attribute Directive for Highlighting

app.directive('highlight', function() {
  return {
    restrict: 'A',
    link: function(scope, element) {
      element.on('mouseenter', function() {
        element.css('background-color', 'yellow');
      });
      element.on('mouseleave', function() {
        element.css('background-color', '');
      });
    }
  };
});

HTML:

<p highlight>Hover to highlight this paragraph</p>

🧾 Adds/removes background color on hover using DOM events.


πŸ§ͺ Example – Element Directive with Isolated Scope

app.directive('userCard', function() {
  return {
    restrict: 'E',
    scope: {
      user: '='
    },
    template: `
      <div class="card">
        <h4>{{ user.name }}</h4>
        <p>Email: {{ user.email }}</p>
      </div>
    `
  };
});

Controller:

$scope.person = { name: "John Doe", email: "john@example.com" };

HTML:

<user-card user="person"></user-card>

🧾 user is two-way bound via = scope binding.


πŸ”„ Scope Binding Options

SymbolBinding TypeDescription
'='Two-way bindingSyncs data between parent and directive
'@'Text bindingPasses strings from attributes
'&'Method bindingExecutes expressions or callbacks in parent

βš™οΈ The link Function in Directives

The link function is used for:

  • DOM manipulation
  • Event listeners
  • Watching scope variables
link: function(scope, element, attrs) {
  scope.$watch('someValue', function(newVal) {
    // React to value changes
  });
}

🧠 Real-World Use Cases for Custom Directives

  • Reusable UI Components: Cards, modals, buttons
  • Form Validations: Custom input rules and behavior
  • Visual Effects: Tooltips, hover effects, transitions
  • Dynamic Layouts: Tabs, accordions, collapsible menus
  • Integration Wrappers: External libraries or widgets

πŸ›‘οΈ Best Practices

βœ”οΈ Use isolated scope for reusable components
βœ”οΈ Keep DOM manipulation inside link function
βœ”οΈ Name directives in camelCase in JS and kebab-case in HTML
βœ”οΈ Use controller and bindToController for complex components
βœ”οΈ Avoid logic in templatesβ€”keep it in controller or link functions


πŸ“Œ Summary – Recap & Next Steps

AngularJS custom directives provide a powerful way to extend HTML and create modular, testable, and reusable components. Mastering them enables you to build flexible UI building blocks and scale your applications efficiently.

πŸ” Key Takeaways:

  • Use app.directive() to define custom behaviors
  • Choose the right restrict type (E, A, EA, etc.)
  • Leverage scope bindings (=, @, &) for flexibility
  • Use the link function for DOM manipulation

βš™οΈ Real-world Relevance:
Perfect for building component libraries, integrating jQuery plugins, validating form fields, and creating a custom design system in AngularJS.


❓ FAQ – AngularJS Custom Directives


❓ When should I create a custom directive?
βœ… When you need reusable behavior or UI that isn’t covered by built-in directives.


❓ What is the difference between directive and component in AngularJS?
βœ… directive() is more flexible for DOM logic, while component() is preferred for encapsulated UI components with a clear structure.


❓ Can I pass data to a custom directive?
βœ… Yes. Use isolated scope bindings (@, =, &) to pass data or functions from the parent scope.


❓ Can custom directives manipulate the DOM?
βœ… Absolutely. Use the link function for DOM tasks like setting styles, adding events, or animations.


Share Now :

Leave a Reply

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

Share

πŸ§ͺ AngularJS Custom Directives

Or Copy Link

CONTENTS
Scroll to Top