Skip to content

Instantly share code, notes, and snippets.

@jacopotarantino
Last active April 23, 2019 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacopotarantino/0d6499f2f73f3e644e4ae5208ea35e4d to your computer and use it in GitHub Desktop.
Save jacopotarantino/0d6499f2f73f3e644e4ae5208ea35e4d to your computer and use it in GitHub Desktop.
angular1-dependency-injection.js

so, in earlier angular1 code, we would list all of the dependencies of a controller in an array where the last item in the array is the controller to inject them into. it looked like this:

someModule.controller('MyController', ['$scope', 'dep1', 'dep2', function MyController ($scope, dep1, dep2) {
  // do something...
}]);

this pattern works but it's ...not great. right? tons of nesting, repetition, people unfamiliar with javascript would be very confused. so then we started using injection syntax.

var MyController = function MyController ($scope, dep1, dep2) {
  // do something...
};
MyController.$inject = ['$scope', 'dep1', 'dep2'];
someModule.controller('MyController', MyController);

this approach has the advantage that it's a lot easier to reason about but it's still roughly the same amount of code and doesn't really solve the duplication problem. later, somebody figured out that we could hack the code a bit and released a plugin that lets us do the following:

function MyController ($scope, dep1, dep2) {
  // do something...
};
someModule.controller(MyController);

this is clearly a much prettier way to read and write controller code with dependencies. we've removed all the duplication of assigning a name to the controller and telling angular which dependencies to inject.

my question to you, dear reader, is HOW does this work? it's a much prettier way to write the code but the code is broken as-is. angular doesn't know what to call the controller and doesn't know what dependencies to inject. but all the same, somebody figured out how to make this work. what hacks could you use to force angular to understand the code as-written?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment