javascript - Uncaught Error : Module 'myApp' is not available! (AngularJS)

标签 javascript html angularjs angularjs-directive angularjs-controller

我正在编写 Angular 教程,但一开始就遇到了问题。加载 myApp 模块会引发错误。如教程中所述,这应该是创建 Controller 的三种方法之一。

这是我正在处理的教程的打印屏幕: Creating controllers in tutorials

当我刷新网页时,我在 Chrome 控制台中收到此错误:

Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

这是我的 HTML 文件

  <html ng-app="myApp">
        <head>
        </head>
        <body>
            <h1>Hello world!</h1>   

            <div ng-controller="MainController">
                {{ 2+2 }}
                <br>
                {{ val }}
            </div>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
            <script src="app.js">
        </body>
    </html>

这是我的 app.js 文件

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

var MainController = function($scope){
    $scope.val = "Main controller variable value"
}

那么我的问题是什么?我想不通。

提前致谢

最佳答案

Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

您的原始问题是由于无效的脚本标签造成的。基本上你的脚本标签没有关闭它需要关闭以便浏览器下载 app.js 文件。脚本标签不会自动关闭,因此它需要一个结束标签。

<script src="app.js">

应该是

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

现在,一旦您修复了该错误,您将遇到另一个错误。

[ng:areq] Argument 'MainController' is not a function, got undefined

由于您使用的是最新的 Angular 版本,即任何 >= 1.3.x 的版本都需要使用 .controller 构造手动注册 Controller 。 See here for more details .

注意 - 这有点令人困惑,因为屏幕截图显示您使用的是 1.2.0(不一定需要显式 Controller 注册),但问题中的片段显示为 1.4.x。

关于javascript - Uncaught Error : Module 'myApp' is not available! (AngularJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33353728/

相关文章:

javascript - 有没有更好的方法来处理触摸设备上的 "hover"事件?

javascript - 从里面关闭一个书签

html - 文件上传输入字段的字符限制是多少?

html - 多个行 block 元素

javascript - Angular 2 - 如何在等待 http 请求完成时阻止 GUI 渲染

javascript - AngularJS - 带有动态模板的指令

javascript - 使用 javascript 检测方向变化

javascript - 主干JS模型: Hiding a dropdown

javascript - 单击打开按钮后创建不必要的空间

angularjs - 使用 Angular,如何将单击事件绑定(bind)到元素并在单击时向下和向上滑动同级元素?