Angular 1.5 components with dependency injection on controllers.

I was looking to convert a web component I wrote as a directive in angular 1.4x to the new syntax in angular 1.5x and became confused about how to handle dependency injection and thought I would write quick post to clear it up for others.

First lets look a standard component in Angular 1.4x code. Notice we specify dependencies using the static $inject property, specifically the $timeout and a custom MyService which would not be supplied to the controller unless we ask for them.

Web Component in Angular 1.4x

Well first step to start the conversion process is to go look at the docs for the new components:

You would read through and find there isn’t a single example showing dependency injection of a non-standard service like $timeout, or custom provider or service like `MyService`shown above.

However there is a hint, if you look at the section: Example of a component tree, and select either of the components: `heroList.js` or `heroDetail.js` it does show that the constructor to the controller is passed three arguments:
`($scope, $element, $attrs)`

It wasn’t clear to me if these were the only parameters that could be passed or if it was still possible to add more through explicitly specifying injection.

After some experimentation it turns out, yes, you can still inject dependencies just like the old controllers, you just have the two extra $element and $attrs which previously were only available in the link function.

Web Component in Angular 1.5x

Also note that although one of the first lines in the docs warn:

When not to use Components: for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable

This might scare you into thinking you wouldn’t have access to the $element, but as we saw above it is passed to the controller and you can still do most of the things the old directives did.

Hope that clears it up for those going through the transition.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store