πŸ› οΈ AngularJS Tooling & Libraries
Estimated reading: 4 minutes 40 views

🧾 AngularJS Decorators & Metadata – Extend Behavior of Services, Directives, and Components (2025 Guide)

🧲 Introduction – What Are Decorators in AngularJS?

While modern Angular (2+) uses TypeScript-based decorators like @Component() or @Injectable(), AngularJS (1.x) supports a different kind of decorator patternβ€”one that allows you to modify or enhance services and directives at runtime.

In AngularJS, decorators are used with the $provide.decorator() method and serve as a powerful way to:

  • Wrap existing services
  • Add logging, caching, or metrics
  • Override or extend directive behaviors
  • Implement cross-cutting concerns like error handling or authentication

🎯 In this guide, you’ll learn:

  • What $provide.decorator is and how it works
  • How to decorate services and directives in AngularJS
  • Use cases for AngularJS decorators
  • Differences between AngularJS decorators and Angular 2+ decorators

🧩 Understanding $provide.decorator in AngularJS

The $provide.decorator() method lets you intercept and modify services before they are injected into any component or controller.

πŸ”§ Syntax:

app.config(function($provide) {
  $provide.decorator('serviceName', function($delegate) {
    // Modify $delegate (original service)
    return $delegate;
  });
});

βœ… $delegate is the original instance of the service being decorated.


πŸ§ͺ Decorate a Service Example

βœ… Original Service

app.service('MathService', function() {
  this.add = function(a, b) {
    return a + b;
  };
});

βœ… Add Logging with Decorator

app.config(function($provide) {
  $provide.decorator('MathService', function($delegate) {
    const originalAdd = $delegate.add;

    $delegate.add = function(a, b) {
      console.log('Adding:', a, '+', b);
      return originalAdd(a, b);
    };

    return $delegate;
  });
});

βœ… Now, every call to MathService.add() will log its arguments before executing.


🎭 Decorating Directives (Advanced Use)

βœ… Extend an Existing Directive

Let’s say you want to modify the behavior of ngClick.

app.config(function($provide) {
  $provide.decorator('ngClickDirective', function($delegate) {
    const original = $delegate[0];

    const newCompile = function() {
      const link = original.link;
      original.link = function(scope, element, attrs) {
        console.log('ngClick triggered:', attrs.ngClick);
        link.apply(this, arguments);
      };
      return original;
    };

    $delegate[0].compile = newCompile;
    return $delegate;
  });
});

βœ… Logs every ngClick usageβ€”perfect for debugging, analytics, or tracking.


πŸ“œ Metadata in AngularJS

AngularJS doesn’t use decorator metadata like Angular 2+’s @Component, @Injectable, or reflection-based @Inject(). Instead, metadata is defined via:

  • Module definitions
  • Dependency injection annotations
  • Directive configuration objects

βœ… Example Directive Metadata

app.directive('helloWorld', function() {
  return {
    restrict: 'E',
    template: '<h1>Hello, {{name}}</h1>',
    scope: {
      name: '='
    }
  };
});

βœ… The metadata here includes restrict, template, and scope.


🧠 Real-World Use Cases for AngularJS Decorators

Use CaseWhat You DecorateWhy
Add logging to services$http, custom servicesDebug API calls
Modify directive behaviorngClick, ngModelAdd validation, logging, tracking
Inject global error handling$exceptionHandlerCatch and report client-side errors
Add cachingAPI servicesReduce server requests, speed up UX
AnalyticsButton/directive usageTrack user behavior

πŸ› οΈ Best Practices

βœ”οΈ Always return $delegate after modification
βœ”οΈ Keep decorator logic minimal and modular
βœ”οΈ Decorate services before application bootstraps
βœ”οΈ Use decorators for cross-cutting concerns (e.g., logging, auth)
βœ”οΈ Avoid mutating too many core directivesβ€”may cause instability


βš–οΈ AngularJS vs Angular (2+) Decorators

FeatureAngularJS (1.x)Angular (2+)
Decorator Syntax$provide.decorator()@Component(), @Injectable()
Applied ToServices, directivesClasses, properties
Metadata UsageConfig objectTypeScript decorators + metadata
Use CaseRuntime service patchingCompile-time annotations
Dependency InjectionFunction parameter stringsTypeScript reflection & metadata

πŸ“Œ Summary – Recap & Next Steps

AngularJS decorators provide a flexible and powerful way to enhance services and directives at runtime. While they differ from TypeScript-style decorators in modern Angular, they still allow developers to inject logic like logging, caching, and tracking across an application.

πŸ” Key Takeaways:

  • Use $provide.decorator to wrap services and directives
  • Decorators help implement cross-cutting concerns
  • Metadata in AngularJS is defined through config objects, not annotations
  • Avoid overuse of decorators on core directives unless needed

βš™οΈ Real-world Relevance:
Useful in legacy AngularJS projects for analytics, debugging, performance optimization, and structured enhancement without rewriting the app.


❓ FAQ – AngularJS Decorators & Metadata


❓ What is $provide.decorator used for in AngularJS?
βœ… It allows you to modify or wrap existing services or directives at runtime before they’re injected.


❓ Can I decorate AngularJS directives?
βœ… Yes. You can override or extend directive compile/link functions using $provide.decorator.


❓ Does AngularJS support TypeScript-style decorators?
❌ No. Those are exclusive to Angular 2+ and use TypeScript metadata reflection.


❓ Where is metadata defined in AngularJS?
βœ… It’s defined in module definitions, directive config objects, and dependency injection annotations.


Share Now :

Leave a Reply

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

Share

🧾 AngularJS Decorators & Metadata

Or Copy Link

CONTENTS
Scroll to Top