Starting AngularJS from the Cordova device ready event without using automatic tools

I am currently using Cordova version 3.3.1-0.4.2 along with Angular 1.2.13

My goal is to manually bootstrap Angular once the 'deviceready' event in Cordova is triggered.

During my testing on a Nexus 5 with the command cordova run android, I encountered the same issue while testing on an iPhone.

To simplify the scenario, the JavaScript is running in the overall document scope. The scripts are loaded before the closing </body> tag.


This method works as intended:

angular.bootstrap(document.getElementById("app"), ["MyApp"]);

However, this approach does not work:

function init(){
  angular.bootstrap(document.getElementById("app"), ["MyApp"]);
}

document.addEventListener('deviceready', function () {
  init();
}, true);

Strange enough, if I add alert("init") to the init function, it shows that the function IS being executed. Furthermore, alerts for (angular) and (document.getElementById("app")) confirm their existence.

I find it puzzling why, even though the init() function is being called, it fails when invoked from the EventListener callback but works perfectly when called directly.

Any insights or suggestions on this matter?

Answer №1

If you're looking for a reliable solution, one approach I've discovered is to bootstrap Angular in the usual way and then incorporate Cordova as a module that returns a promise. This promise gets resolved once the device is ready.

angular.module('fsCordova', [])
.service('CordovaService', ['$document', '$timeout', '$window',  '$q',
  function($document, $timeout, $window, $q) {

    var defer = $q.defer();

    this.ready = defer.promise;

    // A backup plan in case the event isn't received
    // This was necessary with certain Cordova versions
    // when testing with 'cordova serve' in a browser,
    // but it works correctly on an actual device
    var timeoutPromise = $timeout(function() {
      if ($window.cordova){
        defer.resolve($window.cordova);
      } else {
        defer.reject("Cordova failed to load");
      }     
    }, 1200);

    angular.element($document)[0].addEventListener('deviceready', function() {
      $timeout.cancel(timeoutPromise);
      defer.resolve($window.cordova);
    });  
  }
]);

To use:

angular.module('app', ['fsCordova']).

run(['$window', function($window){
  // Initialize Fastclick
  FastClick.attach(angular.element($window.document.body)[0]);
}]).

controller('AppCtrl', ['$scope', 'CordovaService', 
  function($scope, CordovaService){

    $scope.ready = false;

    // When Cordova is ready
    CordovaService.ready.then(
      function resolved(response) {
         $scope.ready = true;  
      },
      function rejected(response){
        throw new Error(response);
      }
    );
  }
]);

You can find this bootstrapped project here on GitHub

Answer №2

If you're looking to manually bootstrap AngularJS after the Cordova deviceready event, here's a helpful approach. You can also find more details on this process here.

'use strict';

var CordovaInit = function() {

var onDeviceReady = function() {
    receivedEvent('deviceready');
};

var receivedEvent = function(event) {
    console.log('Start event received, bootstrapping application setup.');
    angular.bootstrap($('body'), ['c3aApp']); // Manually add and boot AngularJS 
};

this.bindEvents = function() {
    document.addEventListener('deviceready', onDeviceReady, false);
};

//If cordova is present, wait for it to initialize, otherwise just try to
//bootstrap the application.
if (window.cordova !== undefined) {
    console.log('Cordova found, waiting for device.');
    this.bindEvents();
} else {
    console.log('Cordova not found, booting application');
    receivedEvent('manual')
}
};

$(function() {
console.log('Bootstrapping!');
new CordovaInit();
});

I opted for this method because I needed to fetch data from SQLite db on the device for AngularJS configuration before loading AngularJS, as loading AngularJS first was causing issues in my code.

Having used this method for some time now, everything runs smoothly.

// PLEASE DO CHECK THE ORDER OF YOUR .js FILES.

Answer №3

  1. As per the Cordova deviceready documentation, it is recommended to listen for the deviceready event within the onLoad event
  2. You might be encountering a problem with the order of JavaScript libraries

I have shared a solution that I developed which does not rely on deferred initialization using promises. This solution has been thoroughly tested and proven to work consistently on various emulators as well as physical iOS and Android devices. You can find more details about this on my blog.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on sending a JSON object to an EJS javascript loop efficiently

Seeking assistance with passing a Json object named myVar to the home.ejs file below. How should I assign the value to the variable called data? <table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%"> ...

Obtain an array containing both matching and non-matching elements

I'm looking to separate a string into an array made up of consecutive substrings, alternating between matches and non-matches of a specified regular expression. Here's an example: [nonmatch, match, nonmatch, match...] For instance, using the c ...

Does angularjs have the capability to filter content using keywords?

In my MySQL database, I have a total of 30 categories and 450 subcategories that are linked to the main categories in a separate table. Categories Table id _ title _ Keywords 1 _ Animals _ animal, animals, pet, parrot 2 _ Books _ books, book, educat ...

Comparison of performance between Bluebird's promisify and promisifyAll when needing to convert a single method from a module into a Promise

I am curious about the performance variations between using bluebird's promisify and promisifyAll. After conducting performance tests on both bluebird promisify and promisifyAll, I did not notice a significant difference in terms of time and memory u ...

Strategies for enhancing jQuery performance using the find() method

I have a form with an id="test", consisting of various select, input, and textarea fields. My goal is to iterate through each field, check if it's empty, and perform an action accordingly. var editTest= $('#test'); editGeneric(editTest); ...

Issue with Magento site: Clicking on thumbnail photo does not update the large photo on mobile devices

As I navigate through a Magento site, I encounter a problem with the thumbnail images not reloading the larger image when clicked. Instead, the browser jumps to the top of the page and a hash symbol gets added to the URL. Based on this behavior, I suspect ...

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

How can I adjust the dimensions of a radar chart in react-apexchart to make it larger or smaller?

I'm currently working on a project that involves displaying data using radar charts. However, I'm struggling to determine the appropriate size for the radar chart. I am utilizing react-apexcharts and its radar chart feature. import { ApexOptions ...

Trouble encountered during the installation of Ionic

Upon attempting to install cordova and ionic using the command below: npm install -g cordova ionic An error was encountered after running the command: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files (x86)\\nodejs\ ...

Error: self has not been declared

We have come across an obstacle. "Reference Error: self is not defined' When attempting to utilize React-data-grid, the problem arises on the server side when building the nodejs application with webpack. The issue is noticeable in the generated b ...

Can you create an HTML page that does not include any images, screenshots, or descriptions?

I need to design an HTML page that resembles the image linked below, but without relying on any images. https://i.sstatic.net/PwioF.png ...

Transfer all files to a different computer on the local area network using Grunt

Is it possible to transfer all files from one directory to another computer on a LAN using Grunt? For instance, I would like to copy all files from my directory to \192.168.1.10\c$\Projects\TestFolder. How can I achieve this? Thank yo ...

Comparing AngularJS $http with $http.post: A Detailed Analysis

As a newcomer to AngularJS, I am experimenting with sending data to the server and mapping it to a DTO in a REST Service. Here's how I attempted to do it: saveUserUrl = "http://localhost:8080/App/rest/UserManager/saveUser"; var res ...

A guide on how to activate an event when a radio button is selected using jQuery

I experimented with implementing this. When I try clicking on the radio button, the code functions correctly, but the radio button does not appear to be checked and remains unchanged. Any ideas on how to resolve this issue? <p> <input id="p ...

Exploring AngularJS with $crypto and ng-options

I need help with my code. Here are the relevant parts: Angular Code: var app = angular.module('App',['mdo-angular-cryptography']); app.controller('AtvdCtrl', function($scope, $crypto, PassWD, $http){ $scope.frInEtAc ...

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

Sending a request to a JSON file using Ajax

I have 2 questions: 1. I am trying to run this file, but it is not giving any errors or showing results. Please help me identify the problem. 2. I added a dropdown menu in my HTML file, but I'm unsure how to use it to display a list of names. Any sugg ...

How is it possible that the SetTimeout code continues to run even after calling clearTimeout

I have this code snippet within my react component: //some code var timeout = null; //global variable //some more code useEffect(() => { if(...some condition) { console.log('test1'); timeout = setTimeout(() => { ...

Guidelines on resolving the issue of Unsupported platform for [email protected]: requested {"os":"darwin","arch":"any"} (existing: {"os":"win32","arch":"x64"})

Trying to install Parallelshell but encountering a persistent warning. I've checked the package file multiple times without finding a solution. Can someone assist me with this issue? ...

How can I determine if an npm package requires publishing before actually performing the publish process?

I am working on consolidating multiple projects into a single code base, with each project being publishable. In order to optimize our continuous integration process, I aim for my build agent to execute a single command that publishes all the relevant pro ...