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

Valor_ picture Valor_ · Oct 26, 2015 · Viewed 13.5k times · Source

I'm working on angular tutorial and i'm having a problem on beginning. Loading myApp module throws error. As explained in tutorial, this should be one of three ways to create controller.

Here is print screen from tutorial i'm working on: Creating controllers in tutorials

When i refresh web page i get this error in Chrome console:

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.

This is my HTML file

  <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>

This is my app.js file

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

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

So what is my problem? I can't figure it out.

Thank you in advance

Answer

PSL picture PSL · Oct 26, 2015

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.

Your original issue is due to the invalid script tag. Basically your script tag is not closed it needs to be closed in order for the browser to download the app.js file. Script tags are not self closing so it needs a closing tag.

<script src="app.js">

should be

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

Now once you fix that you will get into another error.

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

Since you are using the latest angular version, i.e anything >= 1.3.x needs the controller to be registered manually using the .controller construct. See here for more details.

Note - it is a bit confusing because the screenshot shows you using 1.2.0 (which does not necessarily needs explicit controller registration) but snippet in the question shown 1.4.x.