Unknown developer
Unknown developer

Reputation: 5930

Dependency injection special case

Have a look at the following:

angular.module('myapp').controller('Gallery',Gallery);
Gallery.$inject=['GalleryService'];
function Gallery(GalleryService){...}

angular.module('myapp',[]).service('GalleryService',GalleryService);
GalleryService.$inject=['$http'];
function GalleryService($http){...};

Could someone explain to me why the second block needs [ ] inside angular.module? In case I omit it I am getting Exception Error...

Upvotes: 0

Views: 33

Answers (1)

Passersby
Passersby

Reputation: 1172

angular.module('myapp', []) registers the module 
angular.module('myapp') references an already created module called 'myapp'

You could structure your code like so for a more clear approach:

//Register module
var myapp = angular.module('myapp', []);

//Add controllers, service to already created module
myapp.controller(...);
myapp.service(...);

The second parameter (the empty array) is for other modules you would like to use and is required when instantiating a new module.

https://docs.angularjs.org/api/ng/function/angular.module

Upvotes: 1

Related Questions