Sinan Mujan
Sinan Mujan

Reputation: 53

AngularJS including javascript in HTML

Could someone explain why this is working:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="appLogin">
<head>
    <script src="../Scripts/jquery-2.1.0.min.js"></script>
    <script src="../Scripts/angular.min.js"></script>

    <script src="../Global/config.js"></script>
</head>
<body>

</body>
</html>

But when I try to add my config.js script like this:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="appLogin">
<head>
    <script src="../Scripts/jquery-2.1.0.min.js"></script>
    <script src="../Scripts/angular.min.js"></script>

    <script>
        var element1 = document.createElement("script");
        element1.src = "../Global/config.js";
        document.head.appendChild(element1);
    </script>
</head>
<body>

</body>
</html>

I get:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.13/$injector/modulerr?p0=appLogin&p1=Error%….c%20(http%3A%2F%2Flocalhost%3A49723%2FScripts%2Fangular.min.js%3A17%3A431) 

appLogin is my angular module defined in config.js. In both cases when I use developer tools in my browser I see that the script is loaded but for some reason the second approach is not working?

Upvotes: 0

Views: 90

Answers (3)

Sinan Mujan
Sinan Mujan

Reputation: 53

I got it now. As all of you mentioned, the problem is that appLogin does not exist yet. I solved my problem using document.readyState():

    <script type="text/javascript">
    function getConfig() {
        var element1 = document.createElement("script");
        element1.src = "../config.js";
        document.body.appendChild(element1);
    }
    if (document.readyState === "complete") { getConfig(); }

</script>

Thank you guys. :)

Upvotes: 1

noypi
noypi

Reputation: 991

the second example tries to download and create the module asynchronously.

so, there is a chance that 'appLogin' does not yet exist when angular tries to bootstrap.

unlike the first example, browsers wait for the script tag to finish. so, the document's ready event is not yet fired.

i can remember, that auto-bootstrap begins when the ready event is fired.

Upvotes: 1

Narek Mamikonyan
Narek Mamikonyan

Reputation: 4611

you can try something like this

<script type="text/javascript">
  function getConfig() {
   var element = document.createElement("script");
   element1.src = "../Global/config.js";
   document.body.appendChild(element);
  }
  if (window.addEventListener)
   window.addEventListener("load", getConfig, false);
  else if (window.attachEvent)
   window.attachEvent("onload", getConfig);
  else window.onload = getConfig;
</script>

Upvotes: 0

Related Questions