4

When I use jsfiddle to learn Angular, I got an error like blow:

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.

Thanks @Khanh TO's answer, I solved this problem.

But I don't understand why I can't put code in dom ready event.

So the same error occurs like this:

<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded',function() {
            var app = angular.module('MyApp',[]);
        }, false);
    </script>
</head>
<body>
    <div>
        Hello {{val}}
    </div>
</body>
</html>

So I have 2 questions

1: How should I understand that Angular begins compiling the DOM when the DOM is fully loaded.

2: Since Angular begins compiling the DOM when the DOM is fully loaded, the above code should run correctly, but why an error occurred.

Thanks in advance for your help.

Community
  • 1
  • 1
lam
  • 305
  • 1
  • 2
  • 7

2 Answers2

2

Your code does not create an angular module when it is executed. It simply adds an event listener that will create it in future.

Suppose Angular also listens to DOMContentLoaded to begin compilation, now we have two event handlers listening to same event.
Let's say that a particular browser executes the handlers in the order they were attached. Since angular was loaded before your script, it attached the handler before yours. So angular's event handler will trigger first and it'll start compiling, but the module does not exist at this point of time. The module will be created only when your event handler is executed afterwards. Hence it throws the error.

You should write script that creates the angular module when it's executed, so that when scripts are executed and DOM is ready it'll be available.

T J
  • 42,762
  • 13
  • 83
  • 138
2

you add an event listener on DOMContentLoaded to create an angular module, but the angular add an event listener in order to autoBootstrap when there is a 'ng-app';

the key is the callback of angular execute before yours when the event 'DOMContentLoaded' fired, so it can't find a module named 'MyApp'.

what should you do is put you code directly in tag, like this:

<script>
    var app = angular.module('MyApp',[]);
</script>

But, it is better initialize manully

https://docs.angularjs.org/guide/bootstrap

Mekal
  • 340
  • 1
  • 10