Episode 18 of 25

Custom Directives

Learn how to create your own custom directives to build reusable components.

Custom directives let you create your own HTML elements and attributes — building reusable, encapsulated components.

Basic Custom Directive

app.directive('myGreeting', function() {
    return {
        template: '<h2>Hello from my custom directive!</h2>'
    };
});
<!-- Use as an element -->
<my-greeting></my-greeting>

<!-- Use as an attribute -->
<div my-greeting></div>

Note: Directive names in JavaScript use camelCase (myGreeting) but in HTML use kebab-case (my-greeting).

Directive with Template URL

app.directive('userCard', function() {
    return {
        templateUrl: 'directives/user-card.html',
        restrict: 'E',    // Element only
        scope: {
            user: '='      // Two-way binding to passed data
        }
    };
});
<!-- directives/user-card.html -->
<div class="card">
    <h3>{{ user.name }}</h3>
    <p>{{ user.email }}</p>
</div>
<user-card user="currentUser"></user-card>

Restrict Options

restrict: 'E'    // Element: <my-directive></my-directive>
restrict: 'A'    // Attribute: <div my-directive></div>
restrict: 'C'    // Class: <div class="my-directive"></div>
restrict: 'EA'   // Element or Attribute (most common)

Isolated Scope

app.directive('infoBox', function() {
    return {
        restrict: 'E',
        scope: {
            title: '@',    // One-way string binding
            data: '=',     // Two-way binding
            onSave: '&'    // Expression binding (callback)
        },
        template: '<div><h3>{{ title }}</h3><p>{{ data }}</p></div>'
    };
});