依赖注入特例

时间:2016-05-21 16:35:02

标签: angularjs

看看以下内容:

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

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

有人可以向我解释为什么第二个块在angular.module中需要[] ?如果我省略它我得到异常错误...

1 个答案:

答案 0 :(得分:1)

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

您可以像这样构建代码,以获得更清晰的方法:

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

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

第二个参数(空数组)用于您想要使用的其他模块,在实例化新模块时是必需的。

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