未捕获错误:[$injector:modulerr]实例化模块失败;当有多个“ng-app"”指令

"Uncaught Error: [$injector:modulerr] Failed to instantiate module" when there are multiple "ng-app" directives

本文关键字:指令 quot ng-app 模块 错误 injector 实例化 modulerr 失败      更新时间:2023-09-26

我正在学习AngularJS,当我在实验时,我遇到了这个错误:

Uncaught Error: [$injector:modulerr]实例化模块失败错误:[$injector:nomod]模块'myApp'不是可用!您要么拼错了模块名,要么忘记加载它。如果注册一个模块,请确保指定......0)

下面是我的代码:
<!DOCTYPE html>
<html >
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js"></script>
    <script type="text/javascript">
        function Controller( $scope, $location ){
           //
        }
        function Controller2( $scope, $location ){
           //
        }
    </script>
    <title>Angular JS Application</title>
</head>
    <body >
        <div ng-app="myApp">
            <div ng-controller='Controller' >
                <h1>App1</h1>
            </div>
        </div>
        <div ng-app="myApp2">
            <div ng-controller='Controller2' >
                <h1>App2</h1>
            </div>
        </div>
    </body>
</html>

有谁能解释一下是什么问题吗?

没有要绑定的模块。只需在js中添加以下代码,就可以了

var myModule = angular.module('myApp', []);
var myModule2 = angular.module('myApp2', []);

你只能使用on ng-app per html来自动引导你的应用,但你可以通过手动引导你的应用模块来每页运行多个应用…

这里是一个PLUNKER的例子,显示手动和自动模块引导…

你不能这样做:

<div ng-app="myApp">

,而不需要在JS文件中定义该模块。例如

angular.module("myApp", ["ngRoute", "ngResource"])
. . . 

我已经更新了你的代码,请查看

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js"></script>
    <script type="text/javascript">
        function Controller( $scope, $location ){
            alert("hello me 1");
        }
        function Controller2( $scope, $location ){
           alert("hello me 2");
        }
    </script>
  </head>
  <body ng-app>
        <div >
            <div ng-controller='Controller' >
                <h1>App1</h1>
            </div>
        </div>
        <div>
            <div ng-controller='Controller2' >
                <h1>App2</h1>
            </div>
        </div>
    </body>
</html>

注意

从下次开始,请不要在一个html中使用多个ng-app。如果你需要使用它,那么你可以将一个模块注入到另一个模块中,然后再使用它。

您可以这样定义您的app;

var app = angular.module('myApp', []); 

var app2 = angular.module('myApp2', []);