考虑下面的代码:
部分html文件:
<body ng-app>
<div ng-controller="MainCtrl">{{name}}</div>
</body>
部分js文件:
function MainCtrl($scope) {
$scope.name = "John";
}
我总是将我的 Controller 放在某个模块中,我在 ng-app 中定义其名称。 当我没有定义任何模块时它是如何工作的?
最佳答案
Angular,具有这种“自动发现”功能,如果它们是在全局范围内定义的,则允许它按名称查找 Controller 。
此功能主要用于快速演示/原型(prototype)/概念验证片段,而不是实际应用。
来自 Angular 的 Developer Guide :
NOTE: Although Angular allows you to create Controller functions in the global scope, this is not recommended. In a real application you should use the
.controller
method of your Angular Module for your application [...]
关于空的 ngApp
,如果没有指定名称,那只意味着没有模块可以分配 Controller 、指令、服务,但除此之外一切正常。
关于javascript - ngApp 不使用任何特定的模块名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24054536/