Blog>
Snippets

Extending Angular Directives with Plugin Functionality

Demonstrate the extensibility of Angular Directives by incorporating plugin behavior to enhance their functionality.
angular.module('myApp', [])
  .directive('baseDirective', function() {
    return {
      restrict: 'A', // This directive is restricted to attributes
      link: function(scope, element, attrs) {
        // Base functionality of directive
        element.css('color', 'blue');
      }
    };
  })
  .directive('extendWithPlugin', function() {
    return {
      restrict: 'A',
      require: 'baseDirective', // This directive extends baseDirective
      link: function(scope, element, attrs, baseDirectiveCtrl) {
        // Use or modify base directive behavior here
        // Example: changing color to red, which is the plugin functionality
        element.css('color', 'red');
      }
    };
  });
This AngularJS code block defines two directives within an example app module named 'myApp'. The first directive, 'baseDirective', applies a basic style (blue text) to the element it is attached to. The second directive, 'extendWithPlugin', extends the 'baseDirective' by requiring its presence on the same element. The 'extendWithPlugin' directive modifies the behavior of the 'baseDirective' by changing the text color to red, hence acting as a plugin that enhances the original directive.