我从 Angular 开始,我不明白何时使用或不使用 []
在声明(如果这样调用)模块和 Controller 时。
到目前为止,我明白了:
angular.module('app.prof', []).config(config);
意味着我声明模块 prof
同时angular.module('app.prof').config(config);
意味着我调用它。
但我最终总是得到 []
在 Controller 中而不是在模块中,当我有两个 Controller 时,我不知道该怎么办了。
我只是想了解 Angular :(
编辑:添加更多详细信息
在我的 Angular 项目中,我将 Fuse 主题与一个名为 Yeoman 的东西一起使用(如果我理解得很好的话),所以我从不写 <script>
我自己在任何地方标记。
例如,我有这个模块:
angular
.module('app.prof')
.config(config);
和这个 Controller :
angular
.module('app.prof', [])
.controller('ProfController', ProfController);
我的模块和 Controller 总是以这种方式声明,但有时我会收到诸如“模块未声明”或“ Controller 未声明”之类的错误;让我最终在模块或 Controller 中随机放置括号,直到它起作用。
编辑2:
这是我的主要模块:
angular
.module('fuse', ['app.prof']);
我的教授模块:
angular
.module('app.prof')
.config(config);
和我的教授 Controller :
angular
.module('app.prof', [])
.controller('ProfController', ProfController);
这样,整个事情就顺利进行了。但是当我这样做时:
angular
.module('app.prof', [])
.config(config);
和
angular
.module('app.prof')
.controller('ProfController', ProfController);
我得到:
最佳答案
第二个参数是模块的依赖项。由于您目前没有任何依赖项,因此您有一个空数组 []
。
仅在创建新模块时添加括号(依赖项)。每次当您只想使用相同的模块时,您不应该使用括号。所以最后每个模块应该只用 [] 声明一次。并且每隔一段时间就应该调用没有。
还要确保文件和代码以正确的顺序导入。否则,当您尝试向模块添加 Controller 时,该模块尚未定义。
小例子。具有多个 Controller 的应用程序模块。
angular.module('app', []);
angular.module('app').controller('aCtrl', [ function () {} ]);
angular.module('app').controller('bCtrl', [ function () {} ]);
// ...
长话短说。如果声明模块,则需要括号。如果您想使用该模块,则无需添加它们。
编辑:对于编辑,您需要再次确保以正确的顺序定义和使用所有内容。
以下内容取决于 app.prof
,这意味着 app.prof
声明需要位于此行之前:
angular.module('fuse', ['app.prof']);
这已经表明模块 app.prof
已声明,并且您尝试向其添加配置。当 app.prof 未声明时,您会收到与显示的类似错误:
angular.module('app.prof')
.config(config);
这声明了模块 app.prof
并向该模块添加了一个 Controller :
angular.module('app.prof', [])
.controller('ProfController', ProfController);
这声明了 app.prof
模块并立即向其中添加一些配置:
angular.module('app.prof', [])
.config(config);
这会向名为 app.prof
的现有模块添加一个 Controller :
angular.module('app.prof')
.controller('ProfController', ProfController);
我想你明白了......
对于一种解决方案,您需要按照与此类似的顺序声明它们...如果所有内容都在一个文件中或者您逐个文件加载它们并不重要,但模块声明顺序很重要。
angular.module('app.prof', [])
.config(config);
angular.module('app.prof')
.controller('ProfController', ProfController);
angular.module('fuse', ['app.prof']);
Controller 声明可能会稍后发生,但无论如何您需要注意顺序。正如您所说,fuse
是您需要在之前声明 app.prof
的主模块。
关于javascript - Angular : When to use "[]" in modules and controllers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43143598/