Sometimes I see dependency injection in Angular done like:
angular.module('controllers')
.controller('BooksListCtrl', ['$scope', 'Books', function($scope, Books){
Books.get(function(data){
$scope.books = data;
});
}]);
And sometimes it looks like the following without the array, and just
passing dependencies directly into the function:
angular.module('controllers')
.controller('BooksListCtrl', function($scope, Books){
Books.get(function(data){
$scope.books = data;
});
});
which one is the right way ?
Both
Does it depend on whether you are doing dependency injection on a controller vs directive vs etc?
No
so how are they different ?
Well first form gives you the freedom to handle the dependencies with your own custom name. For example
app.controller('BooksListCtrl', ['$scope', 'Books', function($scope, myOwnBookName){
myOwnBookName.get(function(data){
$scope.books = data;
});
}]);
while second one does not..but both are correct.
Also, you need to be a little cautious while using the first form because you might mistakenly skip a dependency and/or link it with the wrong one.
For example doing something like:
app.controller('BooksListCtrl',['$scope','$window','$rootScope', function(foo, bar){
...
}]);
would be extremely damaging as foo will now point to $scope, bar will point to $window while $rootScope would be undefined. Just keep the order intact and follow proper naming convention.