Reputation: 804
I'm having issues getting 'deviceready' to register from inside of AngularJS. I'm certain this was working before, so I'm not sure what's changed.
If I call 'deviceready' from a global addEventListener, it works, like so:
document.addEventListener('deviceready', function(){
localStorage.deviceReadyGlobal = true;
});
deviceReadyGlobal=true is set. However, if I try to attach this from within Angular, it never fires, like so:
app.run(function(){
document.addEventListener('deviceready', function(){
localStorage.deviceReadyAngular = true;
});
});
deviceReadyAngular is never set. Now, I understand that PhoneGap probably already fired 'deviceready' while Angular was bootstrapping, but according to the PhoneGap docs, that shouldn't matter.
The deviceready event behaves somewhat differently from others. Any event handler registered after the deviceready event fires has its callback function called immediately.
Did something change in the behavior of 'deviceready'?
I'm using Cordova 3.3.0 and Angular 1.2.5 currently.
Upvotes: 6
Views: 5745
Reputation: 254
I've had this issue. For me the problem was having the for cordova.js inside the header.
If you generate a sample project from cordova cli, they have the script tag inside the body.
Once i put it in the body ,like the sample project had it, next to the app-root, i started getting the deviceready event
Upvotes: 0
Reputation: 7015
Either way you could also handle it with DOMContentLoaded
event handler in javascript way
document.addEventListener("DOMContentLoaded", function() {
//alert("Calling DOMContentLoaded");
document.addEventListener('deviceready', function(){
//alert("Calling onDeviceReady()");
initializeYourApp();
}, false);
});
Upvotes: 0
Reputation: 17010
This is how I do it inside my app;
// Create an application module with dependencies
var app = angular.module('myApp', []);
function loadTheApp() {
// Hide splash screen if any
if (navigator && navigator.splashscreen) {
navigator.splashscreen.hide();
}
// Initiate FastClick
FastClick.attach(document.body);
// Boot AngularJS
try {
angular.bootstrap(document, ['myApp']);
} catch (e) {
console.log('errrrrrrrrrrrrrr! ' + e);
}
}
// Listen to device ready
angular.element(document).ready(function() {
if (window.cordova) {
document.addEventListener('deviceready', loadTheApp, false);
} else {
loadTheApp();
}
});
This way if we are inside a device environement then we listen to deviceready event, if not, then we just ignore that event and load our app.
Upvotes: 5