angularjs - Angular dependency injection - I keep seeing two different ways of doing it -


sometimes 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 looks following without array, , passing dependencies directly function:

angular.module('controllers')   .controller('bookslistctrl', function($scope, books){     books.get(function(data){       $scope.books = data;     });   }); 

is 1 right way? depend on whether doing dependency injection on controller vs directive vs etc?

sometimes 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 looks following without array, , passing dependencies directly function:

angular.module('controllers')   .controller('bookslistctrl', function($scope, books){     books.get(function(data){       $scope.books = data;     });   }); 

which 1 right way ?

both

does depend on whether doing dependency injection on controller vs directive vs etc?

no

so how different ?

well first form gives freedom handle dependencies own custom name. example

app.controller('bookslistctrl', ['$scope', 'books', function($scope, myownbookname){     myownbookname.get(function(data){       $scope.books = data;     }); }]); 

while second 1 not..but both correct.

also, need little cautious while using first form because might mistakenly skip dependency and/or link wrong one. example doing like:

app.controller('bookslistctrl',['$scope','$window','$rootscope', function(foo, bar){  ... }]); 

would extremely damaging foo point $scope, bar point $window while $rootscope undefined. keep order intact , follow proper naming convention.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -