Search code examples
javascripthtmlangularjscordovaangularjs-factory

AngularJS/Cordova: How can I get values in my factory after deviceready?


I am trying to use the Cordova Device plugin to get info about the device the user is using. The docs say it can only be called AFTER the deviceready function, so in my .run function I have the following:

.run(function($rootScope, $state, $stateParams) {

    document.addEventListener('deviceready', onDeviceReady, false);

    function onDeviceReady() {
        console.log(device);
    }

 //more functions below

This is working great, I see the device object in the console, however what I really want is to use the device object inside a factory that will sometimes get called BEFORE the deviceready event.

So my question is how can I get make device object available to my factory when it becomes available? I want something like the below code

angular.module('myapp.services.myFactory', [])

.factory('MyFactory', function($q) {

    function getDevice () {
        //if the deviceready event happend and I can access the device object set to variable
        return device;
    }

    return {
        getDeviceInfo: function getDeviceInfo() {
            return $q(function(resolve, reject) {
                if (getDevice()) {
                    //do something with the device object 
                } else {
                   //do something without device object
                }
            });
        }
    };
});

Solution

  • No need to leverage .run here - you should be able to execute everything inside deviceready including your module and factory definitions. Just wrap everything in with this event. I also don't believe you need $q to resolve any promises either. Observe the following simplified pattern...

    function onDeviceReady() {
        // guessing your dependency architecture
        angular
            .module('myapp', ['myapp.services'])
            .module('myapp.services', ['myapp.services.myFactory'])
            .module('myapp.services.myFactory', [])
            .factory('MyFactory', function() {
    
                function withDevice() {
                    /*...*/
                }
    
                function withoutDevice() {
                    /*...*/
                }
    
                return {
                    // turnary. device always available to examine at this point
                    'getDeviceInfo': device ? withDevice : withoutDevice
                }
            });
    }
    
    document.addEventListener('deviceready', onDeviceReady, false);