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