What is the correct way to use Deviceready in an Ionic application?

I am currently working on a mobile application built with Cordova and Ionic. The default page of the application requires the use of the SQLLite plugin.

https://github.com/brodysoft/Cordova-SQLitePlugin

The issue I am facing is that the view contains

ng-init="setData()"

This calls the controller method that works with the SQL Lite plugin. However, this method is triggered before the deviceready event is initialized (the plugin can only be initialized after the deviceready event).

I attempted to implement the following workaround:

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      db = window.sqlitePlugin.openDatabase({name:"callplanner"});
    }

However, this solution did not work for me.

So I tried another approach:

.factory('cordova', function () {
  return {
      test: function(){
          document.addEventListener("deviceready", this.ready, false);
      },
      ready: function(){
            alert("Ready");
            db = window.sqlitePlugin.openDatabase({name:"callplanner"});
      }

  }
})

And in the controller initialization, I attempted:

cordova.test();

Unfortunately, this approach also did not work (devicereadfy is fired after ng-init).

In my search for a solution, I came across this article:

However, I am unsure how to implement a "splash screen" before the app is ready and how to set a timeout.

Does anyone have any ideas on how to solve this problem?

Thank you in advance for any advice or assistance.

Answer №1

To properly initialize your setup, make sure to first handle the "deviceready" event in Cordova before starting the AngularJS app. Follow these steps:

  1. Remove the ng-app attribute from the html/body tag

  2. Initiate the Angular app after devireready event:

    <script>
      document.addEventListener('deviceready', function() { 
        angular.bootstrap(document, ['YourAppName']);
      }, false);
      var YourAppName = angular.module('YourAppName', []);
    </script>
    

For more information, check out these related questions:

  • Cordova + Angularjs + Device Ready
  • Initialize my AngularJS App after Phonegap deviceready

Answer №2

Unfortunately, the @t4deu solution didn't work for me because my ng-app tag was located in the body. I made a small adjustment to see if it might be helpful for someone else facing the same issue.

  <script>
    document.addEventListener('deviceready', function() {
      angular.bootstrap(document.querySelector('body'), ['starter']);
    }, false);

  </script>

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

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

Turn off the autofill option for passwords in Google Chrome

Is there a way to prevent the password autocomplete dropdown from appearing when clicking on the password field? In Chrome Version 61.0.3163.100, none of the solutions seem to be working. Screenshot This issue has been raised many times, but setting autoc ...

Utilizing a server for seamless communication between a mobile device and a website

Exploring a simple setup idea here: Imagine having a mobile app with a page that contains 4 lines of content (utilizing phonegap for development). The plan is to have a web page where data for those 4 lines can be inputted. Once the information is submitt ...

The replace function fails to recognize Cyrillic characters when combined with the /b flag

Struggling with a persistent issue, I've noticed that my code works perfectly with Latin characters but fails to recognize Cyrillic characters when using jQuery. $('p').each(function() { var $this = $(this); $this.html($this.text().re ...

Using regular expressions to extract the value of a specific key from a JavaScript object

After scraping a webpage with BeautifulSoup and requests, I came across this snippet of code within the HTML content: $create(Web.Scheduler, { "model": '{"apt":[0]}', "timeZone": "UTC", "_uniqueI ...

Steps for assigning distinct identifiers to information entered through an input form

I have a question that I just can't seem to figure out: So, I have this input form: <form @submit.prevent="customSubmit"> <label>Name</label> <input type="text" v-model="newUser.name" id=&quo ...

JQuery Ajax request produces the message "Insufficient storage to fulfill this operation."

Encountering an error while attempting to pass the result.target of an OnLoad event in FileReader.readAsArrayBuffer call using a jQuery Ajax POST. The POST is not being executed, and this issue seems to be specific to IE, as it functions correctly in Chrom ...

radio input not reflecting changes in the model

My custom directive is causing issues with updating the model when using input type=radio, although normal text types are working fine. What steps can I take to ensure that the model continues to update properly? app.directive('advformInput', f ...

Consistent sizing for Bootstrap thumbnail images

In my current project, I am implementing a Bootstrap thumbnail feature where each thumbnail consists of an image and a heading. However, a problem arose as the images do not have the same size, resulting in thumbnails with varying dimensions. To resolve th ...

Unusual output from the new Date() function: it displays the upcoming month

Your assistance and explanation are greatly appreciated. I have created a method that is supposed to return all the days of a given month by using two parameters- the year and the month: private _getDaysOfMonth(year: number, month: number): Array<Date& ...

The processing indicator fails to function properly when trying to refresh a jQuery datatable

I am currently customizing the loading indicator for the datatable using a spinner called startLoadGlobal(SPINNER_DATA_TABLE_FINANCEIRO_CARREGAR_REGISTROS) in jQuery. It works correctly when I initially load the datatable, however, when I reload it, the sp ...

Options menu in an Android Studio application

Having just begun my journey with Android Studio, I am facing difficulties in creating a menubar. Despite my efforts to find solutions, none of them seem to work out. I attempted the following code snippet, but I feel stuck at this point: public class Ma ...

What to do when the 'image' property in Next.js next/image has an implicit 'any' type and needs fixing?

I'm a newcomer to Next.js and TypeScript and I can't seem to find any helpful resources on resolving this particular issue: import Image from 'next/image'; export default function Item({ image }) { // <-- parameter image needs a &ap ...

The Mapbox map fails to display properly upon initial page load

When my Mapbox map loads, I am experiencing issues with it only rendering partially. It seems that adjusting the width of the browser or inspecting the page will cause the map to snap into place and display correctly. To demonstrate this problem, I created ...

Ways to access a JavaScript object beyond the function scope

Using the code below, I am able to retrieve JSON data when an element is clicked. This data is then used to create a table, fill the cells with images, and append the table to a specific div. function LoadImagesByCategory() { $.getJSON("/Service/GetJs ...

"Troubleshooting Nextjs in a Production Environment: Tips for Resolving Local Debugging Issues When

Everything is working flawlessly in my nextjs development setup. The build process goes smoothly without any issues. However, when attempting to serve the production locally, an error pops up saying: "Error: Element type is invalid: expected a string (for ...

Is there a way to dynamically update one input field while another input field is being modified? [HTML / JS]

I have a form with 3 input fields. One of the inputs is disabled, while the other two are enabled. The goal is to combine the values entered in the enabled fields to populate the disabled field. How can this be achieved? Is it possible for the value in th ...

The play button in the customized React AudioPlayer may sometimes need to be tapped twice in order to start

I've encountered an issue with my simple audio player (React/Vite) that transitions to the next track automatically or manually. Everything seems to be functioning correctly except for the initial press of the play button. The player opens with the pa ...

Refreshing the data source on a DevExtreme menu is a simple process that can be

Utilizing the angular-translate library for internationalization has its quirks, mainly because the $translate service loads strings asynchronously. Below is a snippet of code from a controller where I need to replace the current datasource items with a n ...

Tips on resetting the position of a div after filtering out N other divs

Check out this code snippet. HTML Code: X.html <input type="text" id="search-criteria"/> <input type="button" id="search" value="search"/> <div class="col-sm-3"> <div class="misc"> <div class="box box-info"> ...