user687554
user687554

Reputation: 11131

Load JavaScript at Runtime in AngularJS

I have an AngularJS app. I want this app to run both in the browser and be able to distribute it with PhoneGap. In an attempt to do this, I have the following code:

index.html

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="/app/app.js"></script>
</head>

<body>
  ...
  <script type="text/javascript">
    if (window.location.protocol === "file:") {
      document.addEventListener('deviceready', startApp, false);
    } else {
      startApp();
    }
  </script>
</body>
</html>

app.js

function startApp() {
  var myApp = angular.module('myApp', ['ngRoute']);
  myApp.config(function() {
    ...
  });

  myApp.run(function() {
    ...
  });
}

controller.js

"use strict";

myApp.controller('MyController', function($rootScope, $scope, $location) {
  ...
});

myApp.controller('MyOtherController', function($rootScope, $scope, $location) {
  ...
});

...

If I add controllers.js after app.js in the head tag, I get an error that says:

Uncaught ReferenceError: myApp is not defined 

This is happening because I'm manually bootstrapping the AngularJS app. I need to manually bootstrap it because of my need to startApp. For this reason, I need a way to dynamically load controllers.js from within startApp. Yet, I'm not sure how to do that. Can anyone provide some help?

THank you

Upvotes: 1

Views: 1164

Answers (3)

user3695936
user3695936

Reputation: 1

First thing first: To initialize your app angular module its require angular-route.js with angular.js file and these js file should be loaded before your app js.

<head>


<script type="text/javascript" src="/app/angular.js"></script>
 <script type="text/javascript" src="/app/angular-route.js"></script>
      <script type="text/javascript" src="/app/app.js"></script>
    </head> 

Upvotes: 0

Devansh
Devansh

Reputation: 1267

you have missed ng-app="" attribute in html tag...

<!DOCTYPE html>
    <html ng-app="myApp">
    <head>
      <script type="text/javascript" src="/app/app.js"></script>
    </head>

    <body>
      ...
      <script type="text/javascript">
        if (window.location.protocol === "file:") {
          document.addEventListener('deviceready', startApp, false);
        } else {
          startApp();
        }
      </script>
    </body>
    </html>

Upvotes: 2

wesleycoder
wesleycoder

Reputation: 1205

Why don't you give requirejs a try? He has a strong dependency management based loader and will avoid issues like this.

Upvotes: 0

Related Questions