What are "decorators" and how are they used?

Kevin Beal picture Kevin Beal · Apr 18, 2013 · Viewed 62.6k times · Source

I'm curious what exactly decorators are in AngularJS. There isn't much information online for decorators save for a blurb in the AngularJS documentation and a brief (albeit interesting) mention in a youtube video.

As the Angular guys put it a decorator is:

Decoration of service, allows the decorator to intercept the service instance creation. The returned instance may be the original instance, or a new instance which delegates to the original instance.

I don't really know what that means, and I'm not sure why you would separate this logic from the service itself. For example if I wanted to return something different under different conditions I would just pass different arguments to the relevant functions or use another function sharing that private state.

I'm still kind of an AngularJS noob so I'm sure it's just ignorance and/or bad habits I've picked up.

Answer

tamakisquare picture tamakisquare · Apr 18, 2013

A good use case of $provide.decorator is when you need to do minor "tweak" on some third-party/upstream service, on which your module depends, while leaving the service intact (because you are not the owner/maintainer of the service). Here is a demonstration on plunkr.