Create, Delete, And Search Contacts In Ionic Framework

When you make an app or service, you may find your self wanting to strengthen the user experience by connecting with friends in some fashion.  Applications like Facebook and Twitter allow you to search your contact book for friends that are already using their service.  If your friend isn’t using the service, you have the option to invite them.

Using native Android and iOS code could make this process very painful for the developer as it is lengthy and difficult.  Lucky for us, we are using Apache Cordova with Ionic Framework and there is a plugin for us that takes all the pain away.

The following steps will show you how to create, delete, and find all device contacts in your Ionic Framework project.

To make this article easy to follow, lets start by creating a fresh Ionic project.

Remember, if you are not using a Mac computer, you cannot add and build for the iOS platform.  You’ll be restricted to only Android.

Since we are relying on native functionality, we now need to add the Apache Cordova Contact’s plugin, which will allow us to access the address book.

Since this tutorial is based on Ionic Framework, we are going to add the AngularJS extension set, ngCordova.  This will allow us to keep consistency in our AngularJS development.  If you’re using Phonegap or another Apache Cordova framework, you’re more than welcome to use the official plugin API.

Download the latest ngCordova release and copy ng-cordova.min.js into your project’s www/js directory.

Open your index.html file and include the script above your cordova.js script.  It will look something like this:

We are almost done including ngCordova into our project.  We only need to inject it into our angular.module in our app.js file like the following:

We are now ready to access the device contacts.  Before we do this, there are a few important things to note:

  • This plugin will not work in the web browser.  To test this, you must be on a device or simulator.
  • The plugin will not function until the $ionicPlatform.ready() or onDeviceReady() methods have fired.   You will get errors or strange results if you try to use before the platform is ready.

With this in mind, open your app.js file and add the following controller with methods:

To start things off, lets focus on our getContactList() method.  This method isn’t documented in ngCordova as of right now, but it does exist.

The object we pass into the .find() method is the same object that exists in the Apache Cordova API.  It is known as the ContactFindOptions and it contains a filter and multiple options.  In my example, I left the filter as an empty string because I want to return all contacts.  If this string contained data, the search would filter the contacts based on it.

The response is an array of objects where each object is a contact in the address book.  The possible items in the object can be seen in the official documentation.

Moving on to the createContact() method.  As of right now this is the only documented method in ngCordova.  It can be used like the following:

Going back to the contact object documentation, we can create a contact using any of those object fields.  In the above example, I only wanted to create a contact with a display name.

The final command in our lesson is for removing contacts.  The setup is pretty much the same as we did for createContact(), but this time we are using .remove() instead of .save().

Since we have all of our back-end methods configured, let’s go ahead and look at our index.html file for front-end awesomeness.

In the above example, notice that we have two buttons in our header and a list.  Tapping the load button will display all device contacts in the list, while tapping the new button will create a new contact.  Based on the simplicity of our code, you will need to tap load again in order to display the new contact.  Get creative and you won’t have this problem.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Matias Tucci

    Great tutorial! Small question: why are you doing ‘cordova build android’ and ‘adb install…’ and not ‘cordova run android’? Thanks!

    • Great question @matiastucci:disqus!

      I don’t use the run command because every time I did, it never worked correctly on the device. I think it failed to clean my project correctly or something which caused me to bang my head quite frequently.

      Since doing things the long way I’ve had far less trouble.

      Regards,

      • Matias Tucci

        Oh, ok. Perhaps livereloading it with ‘ionic run -l android’ do the trick. Thanks!

        • It might. I haven’t used the -l flag before.

          I’ll try it out for a bit. Worst case scenario, I can go back to building with Cordova and installing with ADB.

          • Matias Tucci

            Exactly! I love livereload. Good luck!

  • Oak Krittee

    I want ionic tutorial and example for insert,update,del data from database(SQLServer,MySQL) on server.

    Regards,

  • Keith

    For those following the excellent post and find they only have just the one record returned, add the following to the options array:

    $cordovaContacts.find({filter: ”, multiple:true})

    😀

  • Andrew Barr

    Hello and thanks for the post.

    I have been reading through the plugin code. Do you know if it is possible to use the native contact picker with a filter? Or do we have to style the contacts ourselves if we want to apply filters?

    I ask because the standard picker on Android includes contacts from a ton of apps, and I am just looking for contacts with an email and/or a phone number.

    My feeling is that I will have to do the styling if I want that… fortunately Ionic makes that easy.

  • Venkatesh Angara

    Hi, Nic.I am new to inonic and angularJS. I have been following your tutorial. but i have difficulties in saving the contacts. when i save i am able to save the contact displayname. but not the email.

    this is my HTML code

    and my function

    $scope.saveContact = function(contact){
    $cordovaContacts.save(contact).then(function(result){
    $scope.refreshContacts();
    },function(error){
    console.log(error);});}

    Thanks

    • According to the official Apache Cordova documentation, you must use a ContactField[] not a normal object like I see that you’re doing.

      http://cordova.apache.org/docs/en/3.0.0/cordova_contacts_contacts.md.html#ContactField

      You may want to read the Apache Cordova documentation for other contact elements, then circle back here.

      Regards,

      • Venkatesh Angara

        hi nic, i was able to save the contacts after i followed the docs. but however since yesterday all of a sudden i am having problem. the problem is if the device is in sync with a google account i have the following error

        837415 error TypeError: Cannot read property ‘valueOf’ of null

        but once i remove the google account it is able to display the contacts.

        • Can you please confirm that you are NOT using a web browser, ionic serve, or live reload? These tools only have beta and alpha functionality with Ionic Framework so they are known to cause problems.

          If you’re truly building and installing to a device or simulator, mind sharing the full logs?

          Regards,

          • Venkatesh Angara

            I use live reload. but then i have just installed and with out using live reload. still the contacts are not listed.

          • I think the Apache Cordova plugin might only be for local device contacts, not cloud contacts. You might want to ask the plugin developer to get a for sure answer before we troubleshoot for a bug.

            https://github.com/apache/cordova-plugin-contacts

            Regards,

  • Tolga Yaramis

    Hi Nic..
    How can I get and display the contact photo?

    • The official documentation for that is here:

      http://cordova.apache.org/docs/en/3.0.0/cordova_contacts_contacts.md.html#Contact

      It says that it is part of the Contact object and is returned in base64 format.

      Regards,

      • Tolga Yaramis

        It is also written in documentation .”… or a URL pointing to the image”
        $cordovaContacts returns me a url like “content://com.android.contacts/2541/photo”

        Could you able to get and display a photo of an user in your example?

        Thanks

        • I purposefully leave stuff to be desired in my articles. View it as encouragement to attempt it on your own and ask questions along the way.

          If you’ve tried it on your own and are having trouble, please share your error logs first.

          Regards,

          • Tolga Yaramis

            I tried it and as I have written in my previous email plugin returns me an url which cannot be displayed as an image.
            There is no error in log file.

            Here is the sample code which I have tested..

            $cordovaContacts.find({filter: ”}).then(function(result) {

            for (var i = 0; i < result.length; i++) {
            user.picture = result[i].photos ? result[i].photos[0].value : “img/avatar_default.png”;

            ……

          • What is returned from any of your result[i].photos call? I know it is a URL, but paste the result.

          • Tolga Yaramis

            Hi Nic
            I have already written the result of the url in my first post. The result is:
            “content://com.android.contacts/2541/photo”

          • Sorry, I must have missed that part. Can you tell me how you’re attempting to display ‘user.picture’?

          • Tolga Yaramis

            Nothing special..
            Here is the code.

            I know, it is wrong because the url does not provide any image file but that was the question of me.
            How can get the image source and display it on UI?

            Thanks again

          • I’m assuming that you’re populating $scope.contact with your user object at some point? Can you print out {{contact.avatar}} in your view rather than trying to display it as an image and make sure the value is in fact what it should be?

          • nelaturuk

            Hi am having a similar issue. Is it resolved? I have tried all of the options suggested

        • Arjun

          Add this in the config

          .config([‘$compileProvider’, function($compileProvider) {

          Then in the HTML use

          0″ />

  • Rolando Lopez

    Hi Nic, Thanks for this and the other great ionic framework tutorials you’ve posted. I tried the barcode scanner and it works great. I tried this one however I’m not seeing the list of contacts the way I expect. I’ve coded just as you have in your tutorial but I only get a single blank table cell. Any thoughts?

    • What do your logs say?

      • Rolando Lopez

        Well it turns out displayName was null. when I did contact.name.givenName i saw something, but it was still only one item.

        • Please put your full project on GitHub and I’ll take a look.

          Regards,

  • modasser billah Tishad

    Hello, nic. Thanks for the tutorial but I was thinking how can I check
    whether other people in my contacts are using my app or not? Like, for
    example, viber checks the contact list and lets us know which contacts
    use viber. how can we achieve something like that in ionic apps?It’d be nice to have a tutorial on that. Thanks
    again.

    • I’m pretty sure Viber has a back-end remote server where they store your email address and phone number. Then when you launch their application it compares your address book with all the users they have stored on the back-end server.

  • nelaturuk

    I am not able to display the contact photo. Please suggest a way with this. It gives out the path content://com.android.contacts/2541/photo. But not suyre what to do.

    • Can you share the full contact object?

      • nelaturuk

        var fields = [navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.phoneNumbers, navigator.contacts.fieldType.photos];
        navigator.contacts.find(fields, onSuccess, onError, { filter: “Test”, multiple: true, hasPhoneNumber: true });
        function onSuccess(contacts) {
        $scope.contactTest = contacts[0];
        console.log($scope.contactTest.photos[0].value);
        };

        I am able to print the log value and it shows the same above path mentioned. But when i try to acccess it in the view like this:
        0″>. Nothing shows up in the image.

        I have even tried to add config entry like below am not sure if this is the correct way. I have even tried to add it without the route provider :
        .config(function ($stateProvider, $urlRouterProvider) {
        $stateProvider
        .state(‘contactlist’, {
        url: ‘/contactlist’,
        templateUrl: ‘templates/contactlist.html’,
        controller: ‘ExampleController’
        })

        }, [‘$compileProvider’, function ($compileProvider) {

        }])

        • I had asked for the contact object, not source code. I don’t like looking at source code until a problem has been identified correctly. Please get me the full contact object and we’ll go from there.

          Regards,

          • nelaturuk

            What do u mean by contact object ? I am getting it

  • Tashi Wangdi

    Hi Nic, thank you for a great tutorial. I have been able to load and show contacts on android phone. However, the list shows lots of blank contacts(blank rows). Is there any option in $cordovaContacts to avoid contacts with blank name or numbers. I have tried options.hasPhoneNumber = true; but it still shows blank contact rows. Appreciate your inputs. I am

    • nelaturuk

      I am not sure if this would help. I have had the same issue. What I did was loop through the contacts and find only ones with displayName != “” and phoneNumbers != null. Below is code let me know if this works:

      var result = contacts;

      if (result[i].phoneNumbers != null && result[i].emails != null)

      • Tashi Wangdi

        Thanks nelaturuk. I have done the similar thing. I am displaying only those contacts with result[i].phomeNumbers.length > 0.
        I actually was looking for some options in the plugin itself but haven’t found anything. Thanks again for your suggestions.

  • anuj

    hi nic nice article, I am making app in IONIC framework, but not able to fetch contacts for SIM card . how can i do this in cordova or any ionic plugin?

  • Hari Kishan

    Hi Nic, I did an app according to the steps you have mentioned and its working good with android mobiles but it is displaying only one contact in iPhones, do we need to add any other method for iOS. I have tested in iPhone 4s and iPhone 6, both with iOS 9.1

  • Jessica Thompson

    im going to be adding a contact section into my app where it will find emergency contacts only how would I set this up would it be the same? This will be a medical app where the user will enter personal info but I want it so that the user will be able to call those emergency contacts e.g family members, or the emergency services.

  • uma

    Hi Nic, i’m developing one application which requires user register phone number, later compare the users contacts list with application database like whats app way. could you please help me on this, i’ll be very thankful to you.

    • Why don’t you first tell me what you’ve tried. I’d rather you try and tell me whats not working than me doing it for you 😉

  • Martijn

    Thanks for this! However, when I .save a contact, it just saves it to my contacts directly. Can’t I have a ‘Create contact’ screen open, with the details filled in, just like when adding a new contact via WhatsApp or the regular address book? (before actually saving it to the address book). That would give it a more native feel.

  • Ernst Kimmel

    First of all, great tutorial (for me as a ionic/cordova newbe)! However, I’m getting stuck on a issue when trying to remove a contact (showing contacts and creating them works fine). I get this error in my console when trying to remove the contact: ContactError {code: 0} .., and the contact remains in the list. I tried to Google what errorcode 0 means but cannot find an answer. Does anyone know what could be the problem? Hope somebody can help me out 🙂

    • Ram

      I too have the same issue. Can someone help? Nic Raboy?

  • SIMOSALIM

    TypeError: Cannot read property ‘fields’ of undefined 🙁 🙁

    • What do your logs say? (beyond the error)

      • SIMOSALIM

        —> TypeError: Cannot read property ‘find’ of undefined

        02-24 09:25:54.285 1848-1848/test.application.ma.phoneE/Web Console﹕ TypeError: Cannot read property ‘fields’ of undefined
        at Object.find (file:///android_asset/www/lib/ngCordova/dist/ng-cordova.js:1735:29)
        at Scope.submit (file:///android_asset/www/js/controllers.js:45:23)
        at eval at (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:26457:15)
        at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62386:9
        at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29158:28)
        at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29257:23)
        at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62385:13)
        at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:16583:21)
        at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2948:7)
        at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2937:3) at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:25642
        02-24 09:26:04.045 1848-1848/salim.telemaroc.ma.telefoni E/Web Console﹕ TypeError: Cannot read property ‘fields’ of undefined
        at Object.find (file:///android_asset/www/lib/ngCordova/dist/ng-cordova.js:1735:29)
        at Scope.submit (file:///android_asset/www/js/controllers.js:45:23)
        at eval at (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:26457:15)
        at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62386:9
        at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29158:28)
        at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29257:23)
        at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62385:13)
        at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:16583:21)
        at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2948:7)
        at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2937:3) at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:25642

        • I’m wondering if the plugin changed and it was not updated in the ng-cordova wrapper. You might open a ticket with them.

  • Shash

    Hai Nic… I want to list google contacts in my ionic app…..how can I achieve this..?plz suggest me…

  • Shash

    Hai Nic… I want to list google contacts in my ionic app…..how can I achieve this..?cordova contacts plugin will only work for local phone contacts…plz suggest me

  • Muzammil Ahmed

    How to add contact detail with phone number and display name both?

  • Hari Kishan

    Hi Nic, previously I’m using the plugin you have mentioned in this article to fetch the device contacts and after that I removed the old plugin and added the new plugin “cordova-plugin-contacts”. After I added this plugin I’m not getting the contacts in iOS. How can I fetch the contacts in iOS?

    • So you’re not using the plugin I am discussing?

    • bujji pavani

      i m also facing same problem

  • vipul sharma

    I have applied the ionic contact plugin in my app. I am able to fetch the contacts, but not able to remove the contact.
    I am getting {“code”:0} error in Console.Can anybody knows about the solution for it? I have googled about it but no luck

  • Hi Nic,

    I’m trying to display both the name of the contact (which works ok with your example) and the phone number. If I use, on my html,

    the phone number shows something like : [{“type”: “mobile”,”value”:”600111222″,”id”:”1″,”pref”:false}]

    and if I use {{contact.phoneNumbers.value}] it doesn’t show anything…

    How can I get something like: “displayName” 600111222 ?

    Thanks again
    Abel

  • Love Panchal

    i am not able to delete the contact with this code it showing me error {code:0}
    can any one have an idea for this how to resolve it