Angularjs 使用应用程序名和不使用应用程序名时ngApp行为的差异

Angularjs 使用应用程序名和不使用应用程序名时ngApp行为的差异,angularjs,Angularjs,我有下面的代码,它给出了一个输出:add:1+2=3 <body ng-app> add: {{1}} + {{2}} = {{ 1+2 }} </body> 添加:{{1}}+{2}}={{1+2}} 上面的代码没有ng app指令值,但当我使用指令值编写相同的代码时,行为不同,如下所示: <body ng-app="myApp"> add: {{1}} + {{2}} = {{ 1+2 }} </body>

我有下面的代码,它给出了一个输出:add:1+2=3

    <body ng-app>
      add: {{1}} + {{2}} =  {{ 1+2 }}
    </body>

添加:{{1}}+{2}}={{1+2}}
上面的代码没有ng app指令值,但当我使用指令值编写相同的代码时,行为不同,如下所示:

<body ng-app="myApp">
 add: {{1}} + {{2}} =  {{ 1+2 }}
</body>

添加:{{1}}+{2}}={{1+2}}
产生:
add:{{{1}}+{{2}}={{1+2}}

表示应用程序无法识别角度。为什么呢

表示应用程序无法识别角度。为什么呢

不,这意味着Angular无法识别模块名
myApp

此错误:

未捕获错误:[$injector:modulerr]未能实例化模块 myApp原因:错误:[$injector:nomod]模块“myApp”不可用

指示Angular正在搜索名为
myApp
的模块,但找不到。所以,它坏了

在Angular.js中,您可以看到
模块(通过名称解析)是可选的:

function angularInit(element, bootstrap) {
  var appElement,
      module,
      config = {};

  // The element `element` has priority over any other element
  forEach(ngAttrPrefixes, function(prefix) {
    var name = prefix + 'app';

    if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
      appElement = element;
      module = element.getAttribute(name);
    }
  });
  forEach(ngAttrPrefixes, function(prefix) {
    var name = prefix + 'app';
    var candidate;

    if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
      appElement = candidate;
      module = candidate.getAttribute(name);
    }
  });
  if (appElement) {
    config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
    bootstrap(appElement, module ? [module] : [], config);
  }
}

在最后一行:
bootstrap(appElement,模块?[module]:[],config),它检查模块是否有值,如果没有,则传递一个空数组
[]
。这是一个有效的列表,可供
引导处理。

到目前为止,我知道当您不在ngApp指令中输入名称时。Angular将在库加载后自动查找您喜欢的模块

关于这个错误,它可能是由另一个脚本标记引起的。加载angular后,它会查找您的模块,但不知怎的,您的文件没有加载,因此您最终出现了一些错误

解决方案是:尝试将angular.js和脚本移动到页眉。如果不起作用,则移动到页脚之前。还要注意它们的顺序,如:

<script src="angular.js"></script>
<script src="app.js"></script>

我知道可以通过使用angular.module('myApp',[])来解决这个问题,但为什么它不会首先发生。因为您没有需要命名模块的东西,所以它可以工作。但是,一旦您命名了一个您没有的模块,它就会中断。使用myApp时控制台中是否有任何错误?我会收到以下错误:未捕获错误:[$injector:modulerr]未能实例化模块myApp,原因是:错误:[$injector:nomod]模块“myApp”不可用!您要么拼错了模块名,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。您知道Angular如何解析有名称和无名称的指令吗?我猜Angular有一个
ng app
指令,该指令的独立范围为
@name=ngApp
,如果没有名称,创建一个动态(未命名)模块。是否有关于此的适当文档,因为我在官方文档中搜索过,但找不到。您可以直接查看源代码吗?我做了一个编辑,显示了在源代码中处理这个问题的位置。
angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});