Event queuing in Angular and PhoneGap allows for seamless handling of asynchronous

Here is my code snippet:

app.factory('contacts', function ($rootScope, $q, cordovaReady) {
    return {
        find: cordovaReady(function (filter) {
            var deferred = $q.defer();

            var options = new ContactFindOptions();
            options.filter = filter;
            options.multiple = true;
            var fields = ["displayName", "name", "addresses", "emails"];
            navigator.contacts.find(fields, function (contacts) {
                $rootScope.$apply(function () {
                    deferred.resolve(contacts);
                });

            }, function (error) {
                $rootScope.$apply(function () {
                    deferred.reject(error);
                });
            }, options);

            return deferred.promise;
        })
    };

Here is another part of the code:

app.factory('cordovaReady', function () {
    return function (fn) {

        var queue = [];

        var impl = function () {
            queue.push(Array.prototype.slice.call(arguments));
        };

        document.addEventListener('deviceready', function () {
            queue.forEach(function (args) {
                fn.apply(this, args);
            });
            impl = fn;
        }, false);

        return function () {
            return impl.apply(this, arguments);
        };
    };
});

When I make a call from the controller:

var contactSearch = '';
contacts.find(contactSearch).then(function (contacts) {
    $scope.contacts = contacts;
}, function (error) {
    console.log(error);
});

I keep encountering this error:

ReferenceError: ContactFindOptions is not defined
    at Object.<anonymous> 

I have ensured that I wrapped the function with cordovaReady. Why is this issue occurring?

Answer №1

Have you checked out this solution - Getting Uncaught ReferenceError: ContactFindOptions is not defined

Don't forget to ensure that your app.js is included after cordova.js or phonegap JS in index.html.

I recommend utilizing the ng-cordova wrapper for the contact plugin.

  1. Ensure ng-cordova.js is included before your JS in the index file.
  2. Inject ngCordova into your app module.
  3. Inject $cordovaContacts into your service/factory.

For more information, check out

Example:

 var services = angular.module("services", ['ngCordova']);
    services.service('contact', contact);
    function contact($cordovaContacts, $q) {
        return {
            find : function() {
                var deferred = $q.defer();
                var options = {};
                options.filter = "";
                options.multiple = true;
                $cordovaContacts.find(options).then(function(contacts) {
                    for (var i = 0; i < contacts.length; i++) {
                        if (null != contacts[i].phoneNumbers) {
                            for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {

                                alert(contacts[i].phoneNumbers[j].value);
                                if (null != contacts[i].emails) {
                                    alert(contacts[i].emails[0].value);
                                } 
                                alert(contacts[i].displayName);
                            }
                        }
                        deferred.resolve();
                    }, function(err) {
                deferred.reject();
                alert("error in contact find");
            });
            return deferred.promise;
          };
    };

I hope this response proves helpful for you.

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

Using deconstruction in exporting as default

As I was diving into a new codebase, I stumbled upon this interesting setup: //index.js export { default } from './Tabs' export { default as Tab } from './Tab' //Tab.js export default class Tab extends Component { render() => &ap ...

Hide HTML div on click

Why does the button disappear when I click on it, but the status refreshes? Javascript $( ".refreshstatus" ).click(function(){ $( ".navplayers" ).load('stats.php'); }); CSS .refreshstatus{ font-family:'Noto Sans'; font-w ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

Adjust the stacking order of bars in a vertical chart and exclude negative values with Vega-Lite

I am utilizing this chart as a guide for my current project Explore Vega Editor here https://i.sstatic.net/VGOee.png Is there a way to rearrange the order of the 'Measure' while keeping 'Measure 1' at the top, disregarding its negati ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

Issue with Vue Composition API: Unable to append a property to an object

Currently, I am utilizing Vue's Composition API in my project. However, I have encountered an issue where the template renderer does not recognize changes when I add a property to a ref object. Below is the code snippet that demonstrates this problem: ...

What is the process for creating a pop-up bubble that appears when the cursor hovers over an image displayed within a table using R Shiny?

I am currently working on code that is almost achieving my desired functionality. I want to make it so that hovering over each question mark in the table will trigger a pop-up bubble displaying the help text, rather than having the text appear at the botto ...

exciting command: templateUrl

I am in need of assistance with a particular issue: I am trying to configure settings for an application and would like to utilize the UI-Bootstrap accordion. This is the HTML code I have so far: <accordion close-others="oneAtATime"> <accor ...

The comparison between form submission and AJAX request when transmitting data in JSON format

Working on a complex PHP/Drupal project, our team is facing the challenge of enabling a deep link into a page that requires extensive data to be passed from the originating site. We have full control over both ends so cross-domain issues are not a concern ...

Guide on Capturing Szimek/Signature_Pad using PHP: How to Save Javascript as PHP Variable?

While perusing through StackOverflow, I stumbled upon Szimek/Signature_Pad which allows for the capturing of electronic/digital signatures using Javascript. Even after conducting research, I still find myself puzzled on how to capture the DATA URI into a ...

"Customize the look of the action button in Material-UI's

Is there a way to customize the appearance of action buttons within a Dialog, DatePicker, or TimePicker by accessing the containing div? I'm looking to add padding between these buttons and potentially change the background color of the div generated ...

Tips for ensuring a module.export function completes its request before assigning the returned value to a variable in another JavaScript file

Within my Node.js application, I am utilizing two JS files. One of these files, latlng.js, contains the following code: async function getPlaceDetails(input) { var locationUrl = 'https://www.google.com'; request(locationUrl, (error, respo ...

Error message HMR Webpack was found to be invalid

When using Webpack, I keep encountering the following error message: Invalid HMR message, along with a lengthy JSON string. Unfortunately, I couldn't find any helpful resources to assist me in debugging this issue. Do you have any suggestions? https ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...

Retrieve a comprehensive inventory of all routes within a Vue project and automatically create a sitemap for the website - Vue Project

Imagine I've set up a route like this: import Vue from "vue"; import Router from " vue-router"; import BookRoutes from "./routes/book"; Vue.use(Router) const router = new Router({ routes:[ { path ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Creating a Server-Side Rendered application from scratch

Currently, we are in the process of developing a Nuxt application using npm run generate and deploying it as a Static Site Generator (SSG). However, an issue has arisen where the application is being built as a Client-Side Rendered (CSR) app instead of Ser ...

Is there a method to prevent data loss on page refresh by persisting data stored in a database?

I'm currently developing a commenting feature for a blog using the latest version of NextJs. The text input collects data and sends it to the 'Vercel' hosted database. I am able to successfully fetch the data from the frontend as expected. ...

Translating jQuery to Regular JavaScript Principles

Could someone please provide me with a comparison between various jQuery methods and their equivalent normal Javascript DOM methods? For example: prev() next() before() after() I would greatly appreciate it if you could offer a mapping of jQuery/Javascr ...

Find a specific row in a table using jQuery without requiring any input from the

I want to create a search function that filters results in a table based on user input. The script I have currently works but I need it to only search the first column without requiring the user to click an input field. I want the default value to load whe ...