Wednesday 18 February 2015

Use $inject for Better Dependency Injection

By now we should all be aware that if you minify your AngularJs code without building in some protection against it, then we can easily lose the references we've entered into the factory / controller / etc. without realising until we fill the console up with errors. Since the beginning I've been using the traditional inline array style protection. This is fine if you have only a couple of dependancies, but soon becomes a readability nightmare when you have any more. Whilst reading through the AngularJs Style Guide by John Papa I came to his recommendation of using $inject. I'm now a convert.

Syntax

The syntax for this isn't too different, and I think that I could update all my code to this method a little time. So this is my old syntax:

app.controller('Controller', ['$scope','$http', 'someOtherService', function($scope, $http, someOtherService){}]);

Even with only three dependancies this line only just fits the 120 character width of my editor. This is my shiny new syntax:

app.controller('Controller', Controller);
Contoller.$inject = ['$scope', '$http', 'someOtherController'];
function Controller($scope, $http, someOtherService){}


As you can see, there are a couple of changes that has spread my original one line of code over three lines. First, instead of using an inline anonymous function I've used a function declaration and referenced it as a parameter in the creation of the controller. You'll find that this errors using JSLint, but works nonetheless. This pattern is something that John Papa recommends in many contexts throughout his style guide, and seems to work well with AngularJs. Now in order to protect against minification you need to pass Controller.$inject (where Controller is the name of your controller) an array of strings that correspond to the dependancies you've declared.

How much more elegant is that?

No comments:

Post a Comment