AngularJS – Step 11: Custom Directives (For Java Developers)

image 2

Play Store Application link – Java to AngularJS in 16 Steps – App on Google Play

image 25

Custom directives in AngularJS are powerful tools that let you extend HTML and create reusable components with custom behaviors. If you’re familiar with Java and want to understand AngularJS directives, think of them as custom tags or components in HTML that you can control with JavaScript.

Java Comparison:

In Java, custom components might be created using JavaBeans or custom tags in JSP. Similarly, AngularJS custom directives allow you to create reusable elements with specific behaviors in your HTML.

Java Example (Custom Tag in JSP):

Here’s a simple example of a custom tag in JSP:

<%@ taglib prefix="custom" uri="/WEB-INF/tags/customTags.tld" %>
<custom:welcomeMessage message="Hello World!" />

In this JSP example, custom:welcomeMessage is a custom tag defined in a tag library.

AngularJS Custom Directives

In AngularJS, a custom directive is created to add new behaviors or reusable components. You use the directive function to define it, and you can control how it is used and what it does through its configuration object.

Configuration Object Properties:

  • restrict: Defines how the directive is used (as an element, attribute, class, or comment).
  • template: HTML content used for the directive.
  • templateUrl: URL to an HTML file used for the directive.
  • scope: Defines the scope for the directive.
  • link: A function executed after the directive is compiled, allowing you to add behavior.

Code Example

Let’s look at a practical example. We will create a custom directive that adds a confirmation dialog to a button.

Example HTML with Custom Directive:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <title>Custom Directive Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

  <button confirm-click="Are you sure you want to delete this item?" ng-click="deleteItem()">Delete Item</button>

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

    // Define the custom directive
    app.directive('confirmClick', function() {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.bind('click', function() {
            var message = attrs.confirmClick;
            if (message && confirm(message)) {
              scope.$apply(attrs.ngClick);  // Execute the ngClick action if confirmed
            }
          });
        }
      };
    });

    // Define the controller
    app.controller('myController', function($scope) {
      $scope.deleteItem = function() {
        alert('Item deleted!');
      };
    });
  </script>

</body>
</html>

Breakdown of the Example:

  1. Define the Directive:
  • AngularJS: Use app.directive('confirmClick', function() { ... }) to create the custom directive. It restricts usage to attributes (restrict: 'A').
  • Java Equivalent: Similar to defining a custom tag in JSP or a JavaBean with specific properties.
  1. Directive Behavior:
  • AngularJS: The link function binds a click event to the button. When clicked, it shows a confirmation dialog. If the user confirms, it executes the ngClick action.
  • Java Equivalent: Like adding custom behavior to a Java component, such as a button click event handler.
  1. Usage in HTML:
  • AngularJS: Add the directive to an HTML element using confirm-click="message", and it will manage the confirmation dialog.
  • Java Equivalent: Similar to adding a custom tag with attributes in JSP.

Comparison Table: Built-in vs. Custom Directives

Built-in DirectivesCustom Directives
Predefined by AngularJSDefined by the developer
Ready to use out-of-the-boxCreated using the directive function
Examples: ng-model, ng-repeat, ng-ifExamples: confirm-click, show-on-hover, uppercase-text

Summary

Custom directives in AngularJS allow you to build reusable components and extend HTML with custom behavior. They are created with the directive function and can include various configurations like restrict, template, and link. This is similar to how custom tags or components are defined in Java, but in AngularJS, it’s done directly within your HTML and JavaScript.

Leave a Reply

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