AngularJS错误:$ injector:nomod模块不可用

时间:2015-08-14 09:26:09

标签: angularjs

我正在尝试学习AngularJS并正在创建我的第一页。我遇到了错误:

错误:$ injector:nomod模块不可用(here

我有三个文件:

/index.html
/js/app.js
/js/controllers/MainController.js

他们如下:

/index.html

<!doctype html>
<html>
    <head>
        <tilte>AngularJS Controllers</title>
        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
    </head>
    <body>
        <div ng-app="myApp">
            <h1>Controllers</h1>
            <div ng-controller="MainController">
                <p>{{ message }}</p>
                <form ng-submit="updateMessage(newMessage)">
                    <input type="text" ng-model="newMessage">
                    <button type="submit">Update Message</button>
                </form>
            </div>
        </div>

        <!-- Modules -->
        <script type="text/javascript" scr="js/app.js"></script>

        <!-- Controllers -->
        <script type="text/javascript" src="js/controllers/MainController.js"></script>
    </body>
</html>

/js/app.js

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

/js/controllers/MainController.js

app.controller('MainController', ['$scope', function($scope){
    $scope.message = 'hello';

    $scope.updateMessage = function(message){
        $scope.message = message;
    };
}]);

我哪里错了?

2 个答案:

答案 0 :(得分:3)

避免创建像app这样的全局变量来分配角度模块。相反,angular提供了更好的语法来设置和获取跨多个文件的模块。

App.js

(function() {
    // IIFE (Immediately invoked Function Express) to wrap variables inside the function. it prevents polluting global namespace.
     angular.module("myApp", []);
})();

MainController

  (function() {
     angular.module("myApp") // note [] is missing, it means we're getting a module
        .controller('MainController', ['$scope', function($scope){
            $scope.message = 'hello';

            $scope.updateMessage = function(message){
               $scope.message = message;
             };
        }]);
    })();

答案 1 :(得分:1)

这是一个错字。 当你在html中提取app.js时,你写了scr而不是src。 参见:

<!-- Modules -->
<script type="text/javascript" scr="js/app.js"></script>