DEV Community

Cover image for How to Use Directives in AngularJS with Examples
Kamal Deep Pareek
Kamal Deep Pareek

Posted on

How to Use Directives in AngularJS with Examples

AngularJS, developed by Google, introduced a new way of building dynamic web applications. One of its most powerful features is directives, which allow developers to extend HTML with custom behavior. In this blog, we’ll explore how to use directives in AngularJS, the different types available, and provide real-world examples to help you master them.

What Are AngularJS Directives?

In AngularJS, directives are markers on a DOM element (such as an attribute, element name, or CSS class) that tell AngularJS to attach specific behavior to that element or even transform the DOM.

In simpler terms, directives are instructions that AngularJS uses to enhance HTML functionality.

Why Use Directives?

  • Promote code reusability
  • Simplify complex UI behavior
  • Separate logic from templates
  • Create custom HTML components
  • Improve maintainability

Built-in Directives in AngularJS

AngularJS comes with several predefined directives:

Directive Purpose
ng-model Binds input, select, or textarea to a model
ng-bind Replaces the inner text of an HTML element with model data
ng-repeat Repeats an HTML element for each item in a collection
ng-if Conditionally includes an element
ng-show/ng-hide Show or hide an element based on an expression
ng-click Attaches a function to the element’s click event

Example 1: Using ng-model

<div ng-app=""> <input type="text" ng-model="name"> <p>Hello, {{name}}!</p> </div> 
Enter fullscreen mode Exit fullscreen mode

Explanation:
Whatever the user types in the input box will automatically reflect in the paragraph using two-way data binding.

Creating Custom Directives

While built-in directives are powerful, the real strength of AngularJS lies in creating custom directives to extend HTML.

Syntax

app.directive('directiveName', function() { return { restrict: 'E/A/C/M', template: 'Your template here', link: function(scope, element, attrs) { // behavior goes here } }; }); 
Enter fullscreen mode Exit fullscreen mode

Restrict Options:

  • 'A' – Attribute (e.g., <div my-directive></div>)
  • 'E' – Element (e.g., <my-directive></my-directive>)
  • 'C' – Class (e.g., <div class="my-directive"></div>)
  • 'M' – Comment

Example 2: Custom Directive with Template

var app = angular.module('myApp', []); app.directive('helloWorld', function() { return { restrict: 'E', template: '<h3>Hello World from Custom Directive!</h3>' }; }); 
Enter fullscreen mode Exit fullscreen mode
<hello-world></hello-world> 
Enter fullscreen mode Exit fullscreen mode

Output:
Hello World from Custom Directive!

Example 3: Custom Directive with Scope and Events

app.directive('clickAlert', function() { return { restrict: 'A', scope: { message: '@' }, link: function(scope, element, attrs) { element.bind('click', function() { alert(scope.message); }); } }; }); 
Enter fullscreen mode Exit fullscreen mode
<button click-alert message="AngularJS is awesome!">Click Me</button> 
Enter fullscreen mode Exit fullscreen mode

Explanation:
Clicking the button shows an alert with the custom message.

Understanding link vs compile

  • link function is used to register DOM listeners and manipulate the DOM.
  • compile function is used to manipulate the template DOM before it is linked.

In most cases, you’ll use link, especially for adding event listeners or DOM manipulations.

Advanced Directive Example: Isolated Scope

app.directive('userCard', function() { return { restrict: 'E', scope: { user: '=' }, template: '<div><h4>{{user.name}}</h4><p>{{user.email}}</p></div>' }; }); 
Enter fullscreen mode Exit fullscreen mode
<user-card user="person"></user-card> <script> $scope.person = { name: "John Doe", email: "john@example.com" }; </script> 
Enter fullscreen mode Exit fullscreen mode

Why use =?
This creates two-way binding between the parent scope and directive scope.

Best Practices for Using Directives

  1. Use Isolated Scopes: Prevent scope pollution.
  2. Break into Components: Use directives to encapsulate UI logic.
  3. Avoid DOM Manipulation in Controllers: Use directives for any DOM logic.
  4. Name Directives Clearly: Use dash-case for HTML and camelCase in JavaScript.
  5. Restrict Properly: Use 'E' for components, 'A' for behaviors.

Testing AngularJS Directives

AngularJS makes unit testing easy with Karma and Jasmine. You can test directives by compiling them and checking their behavior in isolation.

Example snippet:

describe('Directive: helloWorld', function() { var element, scope; beforeEach(module('myApp')); beforeEach(inject(function($rootScope, $compile) { scope = $rootScope.$new(); element = $compile('<hello-world></hello-world>')(scope); scope.$digest(); })); it('should render Hello World', function() { expect(element.html()).toContain("Hello World"); }); }); 
Enter fullscreen mode Exit fullscreen mode

Conclusion

AngularJS directives are the cornerstone of building clean, reusable, and interactive components. Whether you're using built-in directives like ng-model or creating custom directives with templates and logic, mastering directives will greatly enhance your front-end development workflow.

If you're an aspiring or experienced AngularJS developer, understanding how directives work—and how to build your own—will help you write modular, maintainable, and dynamic applications that stand out in real-world projects.

Top comments (0)