I’ve previously written about the power of the Ionic CLI, which offers some great tools to developers building mobile apps using web technologies. While Ionic offers a CLI and mobile-optimized UI components, it doesn’t handle native level integration, for example accessing a user’s camera, or contacts. Since Ionic is built on top of AngularJS, we can use Angular to access native plugins, and this is where ngCordova comes in.
ngCordova is a framework that makes the native Cordova API available as AngularJS services. In this post, I’ll walk through setting up ngCordova, and accessing the contacts on a user’s device. First, a few prerequisites. You must have the following installed on your machine:
- Git (If you want to follow along, or create your own repo)
- NodeJS (Installing NodeJS installs its package manager, NPM)
- Bower (You can use NPM to install both Bower and Ionic)
- Ionic (The Ionic install instructions also have you install Cordova)
I’ve created a Git repository that you can checkout and follow along with, or you can create a new repo and progress through the steps on your own.
First, you’ll want to create a new Ionic app by running this command in Terminal:
ionic start ionic-ngcordova
This starts a new Ionic project, in a folder titled “ionic-ngcordova”. That last bit is arbitrary; you can name it whatever you’d like. Also, this will by default use Ionic’s “tabs” app template (there are others, like “blank”, or “sidemenu” available).
Next, a few housecleaning items I tackle with any new Ionic project. In Terminal, change directories (cd ionic-ngcordova) so you’re in the folder Ionic just created, and enable Sass:
ionic setup sass
Next we’re going to add a few directories to the Git ignore list that shouldn’t be included in our repo. To do this, open the project directory in your favorite text editor. For me, that’s Sublime, so I can open the current directory, with the folder structure visible using:
subl ./
With the project open in your text editor, locate the .gitignore file in the root directory. We’re going to add the following lines to the bottom of this file:
hooks/ www/css/ www/lib/
The hooks directory includes native Cordova JS that’s managed by Ionic, the www/css directory contains your compiled CSS (generated by Sass), and the www/lib directory is where Bower places all its assets (check out the .bowerrc file in the root directory for more info here).
With these steps complete, we have a nice clean repo, and you can run the app in a browser or the iOS Simulator via the command line to make sure everything is working:
// Browser ionic serve // OS Simulator ionic emulate ios
Now for the fun stuff. Back in Terminal, in the project root, let’s install ngCordova:
bower install ngCordova --save-dev
This installs the ngCordova package (specifically, in www/lib/ngCordova), and saves it as a dependency in the bower.json file in the app root (The –save-dev flag, a good habit to get into).
Back in your text editor, open up the index.html file, located at www/index.html. This is the root HTML file that your app runs on. Now that Bower has placed the ngCordova library in www/lib/ngCordova, we need to reference ngCordova’s JavaScript file in our app’s index.html file. Include this line after the line that includes the bundled Ionic/AngularJS file:
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
Next, we need to inject ngCordova as a dependency into our AngularJS app. This is done in the app’s primary JS file, located at www/js/app.js. Following the other default controllers and services injected by Ionic, add ‘ngCordova’:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova'])
ngCordova is now available to our app, and we can install and start using any of the native Cordova plugins listed in the ngCordova docs. Let’s see how we’d access the user’s contacts using the $cordovaContacts plugin.
First, we need to install the plugin using Ionic:
ionic plugin add cordova-plugin-contacts
This installs the Cordova Contacts plugin in the plugins directory in the app root. The ‘ionic plugin add’ command is essentially the same as Cordova’s ‘cordova plugin add’. Check out the Cordova docs for more info here.
Now that we have our native plugin installed, let’s emulate using the iOS Simulator, also using the livereload feature of Ionic’s CLI:
ionic emulate ios -l
This will launch the app in the iOS Simulator, and reload in real time as you make code changes in your text editor.
With the app running in the iOS Simulator, we’re only a few steps away from accessing the user’s contacts. First, we need to inject the $cordovaContacts service into the controller where we want to access the contacts from. I think a user would probably access contacts from their Account tab, so let’s open up www/js/controllers.js, and inject $cordovaContacts into the Account controller:
.controller('AccountCtrl', function($scope, $cordovaContacts) {
With the service available to our controller, we’ll add two buttons that will allow the user to select a single contact, or multiple contacts, respectively. Open up www/templates/tab-account.html, and add this markup following the closing tag. This will use the standard Ionic button markup:
<button class="button button-positive button-block"> Get Contact </button> <button class="button button-positive button-block"> Get Contacts </button>
Now for the magic. Our last step is setting up a function to be called when the user touches a button, and calling the $cordovaContacts appropriately based on which button they’ve touched.
First, let’s add the click handlers using Angular’s ng-click directive:
<button class="button button-positive button-block" ng-click="getContact()"> Get Contact </button> <button class="button button-positive button-block" ng-click="getContacts()"> Get Contacts </button>
At this point, your app should look like this:
Lastly, let’s create the functions in www/js/controllers.js. In the AccountCtrl controller, add the following lines after the $scope.settings object:
$scope.getContact = function() { $cordovaContacts.pickContact().then(function(result) { console.log(result); }); } $scope.getContacts = function() { $cordovaContacts.find({multiple: true}).then(function(result) { console.log(result); }); }
If you hit ‘c’ in Terminal, this will enable Ionic’s console logs feature, and you’ll see the contact objects being logged as you touch the buttons. Alternatively, you can launch Safari, then go to Develop > iOS Simulator and visit the full Safari console there.
You’ll notice that touching the “Get Contact” button launches the native iOS contact picker component:
The “Get Contacts” button simply grabs all the contacts on the device and dumps them to the console, in all their gory detail. Creepy:
While ngCordova is the bridge that allows easy access to Cordova plugins via AngularJS, all the Cordova plugins available have more documentation than is found on the ngCordova site. You’ll notice an “Official Docs” link on each ngCordova docs detail page, which points to the original Apache/Cordova documentation, for example the official Cordova Contacts documentation.
Hopefully you can see how in just a few steps, we’re able to setup a new mobile app using Cordova, leverage Ionic’s tools and UI components, and further layer in ngCordova to access Cordova plugins via AngularJS.
Any questions, thoughts, ideas? Let us know!
Want to learn more? Check out Intridea’s posts on Ionic CLI and Ionic Experiments