While not an important feature, you can, using Cordova (or ngCordova in our case) access your smart devices contacts. Various applications like Twitter or LinkedIn are already using this feature to access a list of your friends, so can you.
 
I’m writing this tutorial to show you how easy it is, so just relax and keep reading.
 
 

Note: If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)
 

Preparation

 
This tutorial has some requirements; skip this step if you already have a configured framework environment:
 
  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
In case you don’t have a previous Ionic Framework experience, find more information here: Ionic Framework | Installation Guide.
 

1. Update Ionic & Cordova

 
Before we can update Ionic and Cordova make sure you have the latest nodeJs version. You’ll not be able to download/update latest Ionic Framework without it.
 
Now we can update Ionic and Cordova, older versions may not work with this tutorial:
 
npm update -g cordova ionic
 

2. Create a New Project

 
ionic start IonicContactsDemo blank
cd IonicContactsDemo
 
Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.
 
Lets add appropriate platforms to our project:
 
ionic platform add android
 
For MacOS users, do it like this:
 
ionic platform add ios
 

3. Download ngCordova archive

 
ngCordova is a collection of 63+ AngularJS extensions on top of the Cordova API that make it easy to build, test, and deploy Cordova mobile apps with AngularJS. While we can make this work without ngCordova, it’s much more practical this way. This collection also holds many Ionic Framework compatible plugins.
 
Download ngCordova zip file, here’s site link:
 
Official Site Docs Download Link
 
 
Unzip this archive, find a file name called: ng-cordova.min.js, it should be available at this location: ng-cordova-master\dist\.
 
Open your newly created project directory and copy ng-cordova.min.js to this location: IonicContactsDemo\www\js.
 
Now include this location to index.html located at IonicContactsDemo\www; add it above cordova.js file, like this:
 
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
 

4. Include Cordova Contacts Plugin

 
Add required plugin:
 
cordova plugin add cordova-plugin-contacts
cordova plugin add cordova-plugin-whitelist
 
Install Whitelist plugin only if you’re using Cordova 4.0 +. Without it you’ll receive “Application Error: There was a network error.” error.
 
GitHub - Contacts
 
 
 

Development

 
At this point, you should have everything set up and ready, we can start working on our example.
 
Go to IonicContactsDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:
 
var app = angular.module('starter', ['ionic', 'ngCordova'])
 
Open index.html file, add a controller to ion-content directive:
 
  <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Local Notification Example</h1>
      </ion-header-bar>
      <ion-content ng-controller="ContactsController">

      </ion-content>
   </ion-pane>
 
Initialize this controller in app.js file; don’t forget to inject $cordovaContacts service.
 
app.controller('ContactsController', function($scope, $cordovaContacts, $ionicPlatform) {

});
 
If you’re using Cordova 4+ you will need to check if there’s a Whitelist plugin installed with your project. If you have it, add this security meta tag to your index.html HEAD content:
 
<meta http-equiv="Content-Security-Policy" content="default-src *; font-src data: *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
 
Without it your application will throw an error during the app initialization, after that it will constantly throwing no security meta-tag found. While not a blocking point, constant console log warnings will make it hard to do any debugging.
 
If you want to create a contact use this function:
 
$scope.addContact = function() {
	$cordovaContacts.save($scope.contact).then(function(result) {
		console.log('Contact Saved!');
	}, function(err) {
		console.log('An error has occured while saving contact data!');
	});
};
 
$scope.contact will hold all information about a new contact. Contact properties can be found in a example below.
 
If you want to find a contact(s) use this function:
 
$scope.getAllContacts = function() {
	$cordovaContacts.find({filter : 'Robert', fields:  [ 'displayName']}).then(function(allContacts) { //omitting parameter to .find() causes all contacts to be returned
		$scope.contacts = allContacts;
		console.log(JSON.stringify(allContacts));
	});
};
 
In case you want to return every stored contact the find function should be used like this:
 
.find({filter : ''}).then
 
If you want to delete a contact use this function:
 
$scope.removeContact = function() {
	
	$scope.removeContact = {};   // We will use it to save a contact
	$scope.removeContact.displayName = 'Gajotres'; // Contact Display Name			
	
	$cordovaContacts.remove($scope.removeContact).then(function(result) {
		console.log('Contact Deleted!');
		console.log(JSON.stringify(result));
	}, function(error) {
		console.log('An error has occured while deleting contact data!');
		console.log(JSON.stringify(error));
	});
}	
 
Continue Reading

  • Jailany Mohamed

    The tutorial works perfectly. I have a question, though.. Is there any way to get all the contacts in the phone book without giving any filters?

    • I think though I will need to test it tonight, find function can be used without parameters or like this: find({filter : ”}), both cases should return every contact.

  • Luis Troya

    Is there a way to load all contacts asyncronous?

    I want to load them and keep tracking for any changes. Can you give a hint o example to do this?

  • HI Choi

    Is this code working at ios or browser? When I command $ionic serve, the inspector says
    TypeError: Cannot read property ‘create’ of undefined
    Surely, when I run ios emulator by $ionic emulate ios, it does not working at all.
    Help me please….

    • This is a common Cordova problem. You probably forgot to install plugin or there was an error during the installation.

      TypeError: Cannot read property ‘create’ of undefined

      means navigator object don’t have contacts property:

      navigator.contacts.create

      Exectued this to uninstall:

      cordova plugin remove org.apache.cordova.contacts

      Then add it again:

      cordova plugin add org.apache.cordova.contacts

      And watch for possible errors.

      • casamia

        Thanks. You’re right. The Cordova-plugin-contacts is not installed.
        Though I’m beginner, I didn’t know that cordova-plugin is platform dependent. My mistake is, having included cordova plugin “BEFORE” creating ionic platform.

        “cordova-plugin have to be added “AFTER” ionic platform created.”

        • You gave me an idea, I’ll add this warning to all my Ionic + Cordova plugin(s) related articles, just to be on a safe side.

  • HI Choi

    If you try to build on ios platform with above code, your emulator will not working.

    In the above javascript code, getAllContacts() and removeContact() functions are needed to be modified in ios platform.

    (I didn’t yet try to build in android platform with below code. Because I don’t have android device and android simulator is horribly slow. So if you find any problems to build these code in android platform, please comment it.)

    (I don’t know how pretty indent code in disqus. Copy below code in your editor.)

    $scope.getAllContacts = function() {
    $cordovaContacts.find(
    /* These options are not optional. So filter, multiple, desiredFields options must be stated. */
    {filter : '', multiple: true, desiredFields: [ 'displayName']}
    ).then(function(allContacts) {
    $scope.contacts = allContacts;
    console.log(JSON.stringify(allContacts));
    });
    };

    $scope.removeContact = function() {
    var opts = { //search options
    filter : 'Dragan Gaic', // 'Dragan Gaic'
    multiple: true, // Yes, return any contact that matches criteria
    fields: [ 'displayName', 'name' ], // These are the fields to search for 'Dragan Gaic'
    };
    $cordovaContacts.find(opts).then(function (contactsFound) {
    // contactsFound is array of contact
    contactsFound.forEach(function(con){
    $cordovaContacts.remove(con);
    });
    }).then(function() {
    // ion-content reload
    $scope.contacts = $scope.getAllContacts();
    });
    }

    • Come on, you’re forcing me to take my Mac out of cabinet (it’s locked there 🙂 ) just to test this. 🙂

      Still thank you, I’ll check it.

    • Ninezenith

      Hi, i tried the above code for iOS and it works. It doesn’t seem to work for Android though. On android, if i keep the “desiredFields:[‘displayName’]”, i won’t see any names, phone numbers extracted, it works well if i remove them.

      Is there anyway to have a single piece of code that works for both?

      Thanks in advance

  • hed

    Hi, how i know the parameters of my contact in my phone?
    Because, i think every phone have a difference parameters..
    For example if i save the parameters X,Y,Z, and another phone only have X,Y
    I think i have to know that..
    Thanks a lot for your tutorial, that help a lot.

    • Parameters in what context?

      • hed

        First thanks for your replay.
        For my question i know that contact have a property displayName,
        This is a string
        But i need a way, maybe dynamic way to get all the properties of the contact for every specific phone
        Or that the same for all ios, android phones?

  • Amila Jayasinghe

    Hi..
    I tried your tutorial. But I cannot preview this in ionic view. Is ionic view cannot retrieve the contact list?

  • Geeta Gupta

    downloaded from git. followed instruction…but cud not load contacts of my device

  • Fabian

    Hi, thank you very much for this tutorial! It works fine, if there is a button for loading the contacts. Is it possible to load them when the app starts?

  • Love Panchal

    can any know how to remove contact because the remove contact code is not working it showing in console {code:0}

  • Thushara Dahanayake

    hi,
    I follow this tutorial. it’s work for me. thanks