⚠️ This lesson is retired and might contain outdated information.

$provide.decorator

Brett Cassette
InstructorBrett Cassette
Share this video with your friends

Social Share Links

Send Tweet
Published 11 years ago
Updated 7 years ago

In this lesson Brett will show you how to use $provide.decorator to cleanly add functionality to AngularJS services and keep your concerns wonderfully separated.

Brett Shollenberger: Today, we'll use the decorator pattern to extend the functionality of our Angular services. We'll be creating a system model to display error messages to our user on the view. The model itself will get an error number from the API.

It's a fairly common occurrence that we'll need to parse one format into another format that's ready for presentation. Since this is a presentation concern and not a model concern, we'll want to encapsulate this parsing logic in another portion of our application.

Angular gives us a great method to do this, namely provide.decorator. This will allow us to create a presenter, which is a special type of decorator that creates a bridge between the model layer and the view layer.

Here, we use provide.decorator to decorate our system object and add new methods and properties on the delegated object. This works quite a bit differently from the way the presenter pattern or the decorator pattern works in other languages.

Because we can't sometimes choose the decorator objects and other times not to, Angular's dependency injection system returns singleton objects, meaning there's only one instance of every service.

Still, it makes sense for us to encapsulate our view-specific logic elsewhere so it's easier for us to refactor and understand the different components of our system.

Another reason we may wish to use a decorator in Angular is to extend other external services without diving into their source code or modifying them directly.