Nuno_147 Nuno_147 - 4 months ago 41
AngularJS Question

Initialize my angularJs App after Phonegap deviceready

I have a phonegap app using AngularJS.

On my app I am using the NetworkStatus plugin to confirm the type of connection the mobile phone is using.

On my root route I am resolving a call to a Service which call DeviceService and it responsbile to access the and decide if the connection is on or off. the resove send to the controller (through route resolve functionality) a connectionState variable which declare the state of the connection.

On that route I would like to throw an error if Connection is not available.

Having said that, my problem is the the DeviceReady event is fired after my route is accessed. so my route resolve unable to complete the connection verification.

How can I sync up that my angular app will only start after DeviceReady event is fired ?


Getting the injector module error from AngularJs usually means that you either mispelled the name of the module or angular simply did not find it.

If the Angular app works properly on its own (e.g when not wrapped in phonegap), this means that this issue is in the order the things happens when your index.html is loaded.

  • Cordova/PhoneGap loads your index page
  • Its Webview parses it and loads its scripts tags
  • If some code is not wrapped in functions or objects, it's executed straight away
  • Phonegap sends the event deviceready to tell your app that its bridges with native code are ready

The last 2 operations can occur in both orders but most often in the one I gave you. Thus, if you put your angular module name on the html or body tag through ng-app for instance, angular will try loading it when it finds it.

So, for it to work, you need to :

  • Remove YourAppName from html/body tag
  • Create your angular module normally (its name must match in bootstrap and module calls)
  • Use the deviceready event as the trigger to boostrap your application

For example (short example, nothing but css in head) :

    <div class="app">
        <div id="deviceready" class="blink">
    <script type="text/javascript" src="phonegap.js"></script>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript">
        document.addEventListener('deviceready', function onDeviceReady() {
            angular.bootstrap(document, ['YourAppName']);
        }, false);

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

If you want to understand this on your own, I recommend putting some console.log to get the order of things.
You can aslo use Chrome DevTools remote debugging which works pretty well If you have Chrome 32+ on your pc and android 4.4 on phone, or only pc and you debug on emulator. Quite nice to see the errors and stuff. Debugging webviews is a bit strange at first but really useful to trace errors !

Hope this helps