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

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

Enhancing the model using Sequelize JS

Currently, I am in the process of developing a basic API using Express and Sequelize JS. Recently, I encountered an issue while attempting to update a record with req.School, but no changes seemed to occur. Despite checking the code below thoroughly, I did ...

Is there a way to extract only the value from the most recent request?

While working with VueJS, I have a handler for changes in an input field that looks like this: inputHandler(url, params){ const p = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST&ap ...

Experience a login page similar to Google's with a fully functional back button

I'm currently working on a login page that requires the user to enter their username and have it validated before proceeding. Once the username is confirmed as valid, a new input field for password entry should appear. However, I'm facing an issu ...

The dirtyFields feature in React Hook Form is not accurately capturing all the fields that are dirty or incomplete,

I am facing an issue with one field in my form, endTimeMins, as it is not registering in the formState. I have a total of four fields, and all of them are properly recognized as dirty except for the endTimeMins field. It is worth mentioning that I am utili ...

Restricted to using solely the letters a through z within an angular framework

I need a way to limit user input to just English characters and exclude numbers or any other languages. I've attempted to achieve this using the following directive, but it's not working as expected. Check out my demo on JSFiddle. app.directive( ...

The v-for loop seems to only update the last element instead of all of them, which is incorrect

How can I ensure that all 3 page links in the nav are displayed in 3 languages of user choice? Initially, the language change works fine on page load. However, after clicking on a language change link once, only the last link's language changes instea ...

Tips for including the % symbol in the Y-axis labels on a HighChart graph

I am attempting to incorporate the % symbol after the value of 100 or -100 on the yAxis in the chart shown above. I made an attempt to add the % symbols as follows: quotes.data.frequency_counts[i].negative = Math.round(negative * -1)+'%'; quote ...

Toggle Canvas Visibility with Radio Button

As I immerse myself in learning Javascript and Canvas, the plethora of resources available has left me feeling a bit overwhelmed. Currently, I am working on a dress customization project using Canvas. // Here is a snippet of my HTML code <input type=" ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...

ng-tags-input not functioning as expected with autocomplete feature

When I add a tag by selecting from a list populated using an $http request, the tag is added but the text that I have typed remains with an ng-invalid-tag class. Screenshots: 1) Initially: 2) Typing 3 letters to make an HTTP call: 3) Now after selecting ...

What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem ...

Sending Location Data From JavaScript to PHP via Cookies

I encountered an issue while attempting to send Geolocation coordinates from JavaScript to PHP using Cookies. The error message I am receiving is: Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/samepage.php on line 24 The file name ...

Continuously simulate mousewheel events

I'm trying to make my mousewheel event trigger every time I scroll up, but it's only firing once. Can you assist me with this issue? Please review the code snippet below. $('#foo').bind('mousewheel', function(e){ if(e.o ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

Ensuring no null objects are present in the jQuery each function

In order to iterate through each key value pair in a JSON element and display it, I am encountering an issue where some of the keys have null values. As a result, using $.each is throwing an error: TypeError: obj is null I do not want to remove the null ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Click the button to trigger the pop-up

After creating a photo gallery using a plugin, my goal is to display this gallery when the user clicks on my homepage button. I am unsure how to make this happen and would appreciate any assistance. Below is my button code: <div class="ow-button-base ...

Passing state updates between child components by utilizing the useReducer hook and dispatching actions

Check out this interactive example on CodeSandbox with the code provided and highlighted linting issues: https://codesandbox.io/s/react-repl-bw2h1 Here is a simple demonstration of my current project setup. In a container component, there is an important ...

Implementing a dynamic function with jQuery Tokenize's change event

I'm currently facing an issue with triggering the on change event on the select box from jQuery Tokenize. Below is the code snippet I am working with: <select id="tokenize" multiple="multiple" class="tokenize-sample"> <option value="1"&g ...