Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convention of formatting injected dependencies?

Angular JS Dependencies

Are there any commonly accepted conventions for how to format long lists of dependencies when using inline bracket notation? After browsing through github and the Angular JS Developer Guide, I haven't seen a consistent approach.

I'm not interested in what individuals think is best (sorry), but if there are standard conventions or best practices defined somewhere that I can't find.


Examples

Standard

This is valid, but it extends to column 212. It's also difficult to quickly compare the strings and the arguments.

angular.module('donkey', []).controller('FooCtrl', ['$scope', '$http', 'someCoolService', 'anotherCoolService', 'somethingElse', function ($scope, $http, someCoolService, anotherCoolService, somethingElse) {
}]);

Somewhat better

It's still out to column 87, but it's easy to compare the strings and args.

angular
  .module('donkey', [])
  .controller('FooCtrl', [
    '$scope', '$http', 'someCoolService', 'anotherCoolService', 'somethingElse',
    function ($scope, $http, someCoolService, anotherCoolService, somethingElse) {
  }]);

Functional, but a little weird.

I'm inclined to use this one, since it's compact horizontally and allows for quickly commenting out dependencies. However, it does seem a little weird.

angular
.module('donkey', [])
.controller('FooCtrl', [
  '$scope',
  '$http',
  'someCoolService',
  'anotherCoolService',
  'somethingElse',
  function (
    $scope, 
    $http, 
    someCoolService, 
    anotherCoolService, 
    somethingElse) {
}])

Extra Credit

Is there a way that satisfies JSLint's whitespace checks and also maintains the code collapse ability in Sublime Text 3?

Thanks!


Resources

Angular JS contributor coding rules make no mention of it.

This best practice guide defers to Google, Crockford, etc.

like image 948
reergymerej Avatar asked Feb 16 '14 17:02

reergymerej


1 Answers

I don't know that there is an accepted convention between the three supported methods for injecting dependencies within Angular.

That being said, I am currently working on a very large Angular project, and we consistently use the $inject syntax to define our dependencies. The documentation also seems to be trending in this direction.

So my advice would be this.

Define All Your Dependencies As Objects

var SomeService = function($rootScope, $http, $q){
  this.$rootScope = $rootScope;
  this.$http = $http;
  this.$q = $q;
};

SomeService.$inject = ['$rootScope', '$http', '$q'];

myModule.service('someService', SomeService);

This is going to make it a lot easier to reason about your code, and allow you to seperate out your services, directives, and controllers into different files.

Except for very small applications, I would stay away from using the anonymous declarations and the array syntax for all of my dependencies.

like image 145
Josh Avatar answered Oct 31 '22 20:10

Josh