Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Create, Delete, And Search Contacts In Ionic Framework

TwitterFacebookRedditLinkedInHacker News

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.

ionic start IonicProject blank
cd IonicProject
ionic platform add android
ionic platform add ios

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.

cordova plugin add org.apache.cordova.contacts

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:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
        <script src="lib/ionic/js/ionic.bundle.js"></script>
        <script src="js/ng-cordova.min.js"></script>
        <script src="cordova.js"></script>
        <script src="js/app.js"></script>
    </head>
    <body ng-app="starter">

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:

angular.module('starter', ['ionic', 'ngCordova'])

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:

example.controller("ExampleController", function($scope, $cordovaContacts) {

    $scope.getContactList = function() { }

    $scope.createContact = function() { }

    $scope.removeContact = function() { }

});

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.

$scope.getContactList = function() {
    $cordovaContacts.find({filter: ''}).then(function(result) {
        $scope.contacts = result;
    }, function(error) {
        console.log("ERROR: " + error);
    });
}

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:

$scope.createContact = function() {
    $cordovaContacts.save({"displayName": "Steve Jobs"}).then(function(result) {
        console.log(JSON.stringify(result));
    }, function(error) {
        console.log(error);
    });
}

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().

$scope.removeContact = function() {
    $cordovaContacts.remove({"displayName": "Steve Jobs"}).then(function(result) {
        console.log(JSON.stringify(result));
    }, function(error) {
        console.log(error);
    });
}

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.

<body ng-app="starter">
    <ion-pane ng-controller="ExampleController">
        <ion-header-bar class="bar-stable">
            <button class="button" ng-click="getContactList()">Load</button>
            <h1 class="title">Ionic Blank Starter</h1>
            <button class="button" ng-click="createContact()">New</button>
        </ion-header-bar>
        <ion-content>
            <ion-list>
                <ion-item ng-repeat="contact in contacts">
                    {{contact.displayName}}
                </ion-item>
            </ion-list>
        </ion-content>
    </ion-pane>
</body>

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

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