Fiddle
解决方法
>如何以及为何使用?
除非有该应用程序的入口点,否则Angular将无法并且无法正确引导应用程序.根据documentation,如果没有传递用于命名app实例的参数,angular将通过爬行DOM并使用遇到的第一个ngApp指令实例来尝试为您提供auto-bootstrap应用程序.
我们通常希望将我们的入口点放在< body>上.元素包含我们需要的所有潜在DOM,而不会使用< head>进行混乱.元素,例如加载脚本和css.也就是说,如果您是自动引导您的应用程序,建议的位置是在HTML元素上.
>我们如何为这个无名模块分配控制器,指令等?
模块,控制器等必须附加到某些东西上,以便Angular接收它们并正确地与它们进行交互.
一旦应用程序被引导,Angular将开始解析DOM,寻找指令.如果您有一个应用程序实例(并且确实如此),您的控制器将自动添加到该实例中.如果你看一下bootstrap文档 – >自动初始化,您将找到以下内容:
Angular initializes automatically upon DOMContentLoaded event or when
the angular.js script is evaluated if at that time document.readyState
is set to ‘complete’. At this point Angular looks for the ng-app
directive which designates your application root. If the ng-app
directive is found then Angular will:
- load the module associated with the directive.
- create the application
- injector compile the DOM treating the ng-app directive as the root of
the compilation. This allows you to tell it to treat only a portion of
the DOM as an Angular application.
>小提琴是如何工作的?
这个实际上是烟雾和镜子真的不应该算:).如果您查看JSFiddle的网络流量,您会发现AngularJS实际上正在加载.因此,插值实际上是自动绑定到JSFiddle Angular实例,而不是您自己提供的(或者在这种情况下没有),解析并随后作为2呈现到DOM中.