Initialize my angularJs App after Phonegap deviceready

后端 未结 5 1426
小蘑菇
小蘑菇 2020-12-08 11:45

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

5条回答
  •  清歌不尽
    2020-12-08 12:12

    I'm using the following solution, which allows AngularJS to be bootstrapped when running with Cordova as well as when running directly in a browser, which is where much of my development takes place. This makes sure that Angular starts up after Cordova/Phonegape is ready, and still ensures that it works when there is no Cordova/PhoneGap at all.

    // This is a function that bootstraps AngularJS, which is called from later code
    function bootstrapAngular() {
        console.log("Bootstrapping AngularJS");
        // This assumes your app is named "app" and is on the body tag: 
        // Change the selector from "body" to whatever you need
        var domElement = document.querySelector('body');
        // Change the application name from "app" if needed
        angular.bootstrap(domElement, ['app']);
    }
    
    // This is my preferred Cordova detection method, as it doesn't require updating.
    if (document.URL.indexOf( 'http://' ) === -1 
            && document.URL.indexOf( 'https://' ) === -1) {
        console.log("URL: Running in Cordova/PhoneGap");
        document.addEventListener("deviceready", bootstrapAngular, false);
    } else {
        console.log("URL: Running in browser");
        bootstrapAngular();
    }
    

    If you run into problems with the http/https detection method, due to, perhaps, loading a Cordova app into the phone from the web, you could use the following method instead:

    // This method of user agent detection also works, though it means you might have to maintain this UA list
    if (navigator.userAgent.match(/(iOS|iPhone|iPod|iPad|Android|BlackBerry)/)) {
        console.log("UA: Running in Cordova/PhoneGap");
        document.addEventListener("deviceready", bootstrapAngular, false);
    } else {
        console.log("UA: Running in browser");
        bootstrapAngular();
    }
    

    You would still need the bootstrapAngular function from the first example, of course.

提交回复
热议问题