Getting Started with ngCordova

Tweet about this on TwitterShare on LinkedIn1Share on Google+8Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page

In this post, we will take a quick dip into ngCordova and Ionic Framework. We will take a look at setting up ngCordova with IonicFramework, add adding a few cordova plugins and testing it out on a device.

This post is not limited to IonicFramework. You can use the same knowledge with Onsen UI or any mobile hybrid application that is powered by Angularjs.

We are not going to build any specific app, but we will add a few plugins to a demo app and see how it works. This would be the list of plugins we would test drive

Screenshot_2015-03-08-18-52-26

You can find the complete code here. You can use this repo to submit the app we create to Phonegap Build Service.

So, let us get started.

Prerequisites

Before we proceed, you need to have a good understanding of Angularjs, IonicFramework or Onsen UI and Phonegap/Cordova.

Since we are going to work with device specific features, you would need an actual device to test your code. This setup will not run in a browser. Some of the features we are working on, may work on an emulator. Make sure you have setup everything on your machine so you can deploy the code to your device. You can refer PhoneGap 3 CLI Setup on Mac & Windows for more information.

Also, we will be using bower to add ngCordova to our project. Make sure you have git installed on your machine and run

npm install -g bower

Setup Project

Assuming that you have already done

npm install -g cordova ionic

We will scaffold a new Ionic app. Create a new folder named ionCordova. Open a new terminal/prompt here and run

ionic start ionCordova sidemenu

Then run

cd ionCordova

And then

ionic serve

This will launch the side menu template in your default browser.

Next, we will be deploying the app to the phone and testing the base project out. For that, we first need to add the respective platform. I have an Android device, so I will be building a project close to Android.

ionic platform add android

Next, we will install the side menu template on our device. Run

ionic run

Once the app is successfully deployed on to your device, you should see

Screenshot_2015-03-08-17-04-54

Debugging Hybrid apps on Android with Chrome

I highly recommend using  chrome://inspect (Remote Debugging on Android with Chrome) while working with Android devices. You can access your app inside the web-view and debug as if you were working with your app in a browser.

Here is a quick snapshot

Screen Shot 2015-03-08 at 17.08.19

ngCordova

ngCordova was built to help make app development faster and more efficient than ever before. It gives you simple AngularJS wrappers for the most popular Cordova and PhoneGap plugins available, where you can take a picture, scan a barcode, upload a file, turn on your flashlight, get your current location, and much more with just a few lines of code.

Pretty simple! As of today, there are around 63 plugins in the ngCordova arsenal. These wrapper make interacting with device specific features pretty easy.

Setup ngCordova

To setup ngCordova, we will be using bower. Run

bower install ngCordova --save

Next, we will add a reference to it in our index.html. Open www/index.html and update it as below

Notice line 21. ngCordova should be after ionic bundle and before cordova.js reference. This is very very important.

Test ngCordova Setup

To  test the setup, we will print the basic device information on the screen. For that, we will be using the org.apache.cordova.device plugin. This is installed by default if you scaffold an Ionic app.

If you want to explicitly add it, run

cordova plugin add org.apache.cordova.device

First we will inject ngCordova as a dependency to our app. Open www/js/app.js and update

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

to

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

And then, we will update our UI to show the device information. Open www/templates/playlists.html and update it as below

Finally, we will update the PlaylistsCtrl you can ignore the names for now, we will clean up later on. Open www/js/controllers.js and update it as below

Things to notice :

We have removed all the code that we are not going to use.

Line 5 : We have injected $ionicPlatform, $scope and $cordovaDevice as dependencies

Line 6 : This is very important. All your ngCordova code SHOULD be written inside  $ionicPlatform.ready(). Else you will see a lot of undefined errors.

Line 7 : This is only a precaution. There are many instance, when the $scope does not update, so we are wrapping our  $cordovaDevice features inside a  $scope.$apply() so that Angular forces a model update.

Line 11 : We get the device object from $cordovaDevice.getDevice() and from that we extract the information needed as shown from lines 13 to 17 and add it to scope.

That is it!

Save all the files and execute

ionic run

And you should see

Screenshot_2015-03-08-17-25-43

Simple and easy!

Refactor Code

Since we would be working with a set of cordova plugins, we will refactor this template.

Step 1 : Open www/templates/menu.html and update it as below

We have removed the old menu items and added a few of the plugins which we are going to test drive here.

Step 2 : Open www/js/app.js  and update it as below

Added routes for each plugin template.

Step 3 : Open www/js/controllers.js  and update it as below

Step 4 : Rename www/templates/playlists.html to device.html

Step 5 : Delete

  • www/templates/browse.html
  • www/templates/login.html
  • www/templates/playlist.html
  • www/templates/search.html

Step 6 : Create

  • www/templates/battery.html
  • www/templates/camera.html
  • www/templates/motion.html
  • www/templates/notification.html
  • www/templates/network.html
  • www/templates/pin.html
  • www/templates/share.html
  • www/templates/sqlite.html
  • www/templates/toast.html
  • www/templates/vibrate.html

And add the following code into all of them

Save all the files and execute

ionic run

The app should be deployed to your device and there should not be any change in the output. Instead, you should see the update menu

Screenshot_2015-03-08-18-52-26

Since we have already implemented the Device API, we will move on to the Battery API

Battery Plugin

Service : $cordovaBatteryStatus

The BatteryStatus plugin provides an API for the current battery status.

Add battery status Plugin

cordova plugin add org.apache.cordova.battery-status

Open www/js/controllers.js and add the below code

As always we wait for the $ionicPlatform.ready(). Then we register  status event on  $cordovaBatteryStatus. When the value changes, the callback will be called, where we set the  batteryLevel and  isPluggedIn values in scope.

But for some reason the above code does not work. The callback never gets called. But If I use the commented code, it works fine. The same code is used in Loved One Notifier.

Next, open www/templates/battery.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-19-30-00

As mentioned, the battery status is never invoked.

Camera Plugin

Service : $cordovaCamera

This service makes it easy to use the org.apache.cordova.camera plugin to take pictures and video from a device.

Add Camera Plugin

cordova plugin add org.apache.cordova.camera

Open www/js/controllers.js and add the below code

We define a set of options on which the image would be captured. And when the takePicture() is called, we take a picture and once the user accepts, we show a preview on the page.

Next, open www/templates/camera.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-19-41-07Once the image is captured after clicking Take a Picture button, the same image preview will appear below.

Screenshot_2015-03-08-19-43-06

Device Motion Plugin

Service : $cordovaDeviceMotion

This plugin provides access to the device’s accelerometer. The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation, in three dimensions along the x, y, and z axis.

Add Device Motion Plugin

cordova plugin add org.apache.cordova.device-motion

Open www/js/controllers.js and add the below code

The logic is pretty straight forward. On line 4, we get the Acceleration at that moment. And on line 21, we keep watching the acceleration params and update the UI accordingly.

Next, open www/templates/motion.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-19-57-59

Notification Plugin

Service : $cordovaLocalNotification

The essential purpose of local notifications is to enable an application to inform its users that it has something for them — for example, a message or an upcoming appointment — when the application isn’t running in the foreground. They are scheduled by an application and delivered on the same device.

Add Notification Plugin

cordova plugin add de.appplant.cordova.plugin.local-notification

Open www/js/controllers.js and add the below code

A new notification can be triggered using the  $cordovaLocalNotification.add(). And the rest is taken care by cordova!

Next, open www/templates/notification.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-20-15-49

And when the  notification is fired (observe the notification bar)

Screenshot_2015-03-08-20-15-58

And finally in the notification panel

Screenshot_2015-03-08-20-16-08

Network Plugin

Service : $cordovaNetwork

The essential purpose of local notifications is to enable an application to inform its users that it has something for them — for example, a message or an upcoming appointment — when the application isn’t running in the foreground. They are scheduled by an application and delivered on the same device.

Add Network Plugin

cordova plugin add org.apache.cordova.network-information

Open www/js/controllers.js and add the below code

Next, open www/templates/network.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-20-31-47

Pin Dialog Plugin

Service : $cordovaPinDialog

PhoneGap numeric password dialog plugin for Android and iOS.

Add Pin Dialog Plugin

cordova plugin add https://github.com/Paldom/PinDialog.git

Open www/js/controllers.js and add the below code

When the page loads, we show a pin dialog. The user enters a Pin to access the app. Here you can grant access or reject access to the screen based on this logic. For this demo, once the user enters a pin, we show it to the user in a dialog and then print it on the screen.

Next, open www/templates/pin.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-20-48-05

Screenshot_2015-03-08-20-48-23Social Sharing Plugin

Service : $cordovaSocialSharing

Share images, text, messages via Facebook, Twitter, Email, SMS, WhatsApp, etc using this plugin.

Support

Screen Shot 2015-03-08 at 21.18.17

Add Social Share Plugin

cordova plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git

Open www/js/controllers.js and add the below code

The nativeShare()  invokes the  $cordovaSocialSharing.share() which triggers the native share sheet. When the user selects an app to share the code with, the message, subject and link will be passed on based on the selected app.

Next, open www/templates/share.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-21-25-46 Screenshot_2015-03-08-21-25-56 Screenshot_2015-03-08-21-26-14

SQLite Plugin

Service : $cordovaSQLite

Native interface to sqlite in a Cordova/PhoneGap plugin for Android/iOS/WP(8), with HTML5 Web SQL API

Add SQLite Plugin

cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git

Open www/js/controllers.js and add the below code

You can know more on how to work with SQLite here. The above code is a excerpt of the same. It creates a new table and adds some data.

Next, open www/templates/sqlite.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-21-58-27Toast Plugin

Service : $cordovaToast

This plugin allows you to show a native Toast (a little text popup) on iOS, Android and WP8. It’s great for showing a non intrusive native notification which is guaranteed always in the viewport of the browser.

Add Toast Plugin

cordova plugin add https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin.git

Open www/js/controllers.js and add the below code

Simple API to show toasts, with duration and position.

Next, open www/templates/toast.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-22-06-34 Screenshot_2015-03-08-22-06-48Vibrate Plugin

Service : $cordovaVibration

Vibrate the device programatically.

Add Vibrate Plugin

cordova plugin add org.apache.cordova.vibration

Open www/js/controllers.js and add the below code

Using the $cordovaVibration.vibrate()  we show a simple vibration pattern.

Next, open www/templates/vibrate.html and update it as below

The output when you execute  ionic run,

Screenshot_2015-03-08-22-17-28Don’t ask how the above image proves that the device vibrates when clicked on the button. You have to take my word for it!

With this, we have test driven a few ngCordova plugins and seen how they can be used. The ngCordova docs are pretty good. You can rely on them quite well for results.

If you are facing issue, do post a comment, but before that please check this guide. Hope this post gave you a decent idea on how to work with ngCordova.


Thanks for reading! Do comment.
@arvindr21

Tweet about this on TwitterShare on LinkedIn1Share on Google+8Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page
  • Manikanta

    device id not working can anyone help ???

  • h2o

    I just tried this example project, but i have issues on Android.
    Especially with the SQLite plugin.
    When I select the SQLite from the side menu, it displays the previously selected menu and
    then stucks on this menu regardless off selection (so, the menu works, but always shows the
    last selected menu option before the SQLite selection).
    My phone is on 4.2.2.
    Where is the problem?

  • Geo

    And $cordovaBarcodeScanner ?????

  • Siva

    Excellent Information !!

  • Neha

    I get this issue Error: device is not defined. it bugs me.Can you tell me how to get rid of it and get this work properly

  • Mark Aurit

    Would have been great to see an example of changing of processing (such as changing the template) based on the device orientation (portrait vs landscape)

  • Pedro Sacramento

    I just would like to say thank you, and that this is one of the best tutorials I’ve ever seen in my ~18 years of programming experience. I’m talking seriously. Congratulations for such an effort, I’m sure that it took a long time to write it so clearly and with so many details. Thank you again.

  • delijati

    “// sometimes binding does not work! :/” this comment fixed a bug , i was struggling for some days 😀

  • 文壮 刘

    Great Tutorial, but I have a question with Camera, when I run this app in my phone(Android 5.1),and select a pic or took a pic, and then the app was waiting and waiting, couldn’t go to “Image Cropping”.

  • Gaurav Bansal

    Great Post!!!!
    But i am facing issue in creating apk of this app, Can you please explain how we create apk of this app? or which folder need to deploy it on adobe phonegap?

  • Richard Bown

    Great post and good introduction to a really interesting and useful platform.

  • Josh Hicks

    wow, using that $scope.apply() to update the $scope just saved my life!!! Thanks for the awesome tutorial. Do you have any for the ngCordova File plugin?

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks Josh. File plugin to read files?

  • Angelo Rigo

    Great Tutorial, i would be good to see one about using ng-cordova device orientation.

  • Payam A

    can you please add a example of ng cordova-background-geolocation thanks

  • Faizan Shakeel

    how do i send user to a specific page on clicking notification when app’s state is ‘background’?

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      You can try Push notification for that. It is more reliable.

  • Mahesh

    Hi Arvind, when i am reading ur articles i am feeling better and confident. Even this article is awesome. But i configured SQLite as u described, I am not getting any message. You can see in attachment. any suggestions? I am unable to find error

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks Mahesh. What is the make & model of the device?

    • 张达

      try change var db = $cordovaSQLite.openDB({
      name: “demo.db”
      });
      to var db = $cordovaSQLite.openDB(“demo.db”);

  • https://github.com/leob Leo van den Bulck

    Excellent tutorial, one remark: I had to remove the extra ‘$scope.apply’, so I had to change:

    $ionicPlatform.ready(function() {
    $scope.$apply(function() {
    …….

    to simply:

    $ionicPlatform.ready(function() {
    ……

    because otherwise Ionic/angular would complain that the scope had already been started.

    Probably due to a change in a recent version of Ionic (I’m using 1.0.0-rc.5).

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks Leo! I did not test this project in 1.0.0-rc.5, that could be the reason. When I wrote the tutorial, there were issues with the operations not written inside the $scope.$apply().

      Thanks for the update!

      • https://github.com/leob Leo van den Bulck

        You’re welcome, keep up the good work!

  • Ismaele Bottelli

    Hi 😀 nice tutorial, i have a question: when the event online is fired (or isOffline) in ng-cordova network state, sometimes happen that the event is run some times. It’s a bug or something?

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks Ismaele! Not sure if it is a bug or not but make sure that you have registered the event inside platform ready method and the callback for the online and offline event runs inside $scope.$apply(). Despite these two changes if the callback is intermittent, we can try and isolate the root cause.

      • Ismaele Bottelli

        Thanks Arvind! Sorry i’m a newbie with cordova plug-in. I use this for a Ionic project, and i don’t really understand how to proceed.. i need to change the code in this way? Could you explain it with an example? Sorry for the request, but you really help me! Thanks anyway 😀 (And sorry for my bad english!)

        • http://thejackalofjavascript.com/ Arvind Ravulavaru

          If you see all the logic inside the NetworkCtrl is wrapped in a $ionicPlatform.ready(). One extra thing you need to do is trigger the $scope.$apply in the online and offline listeners like

          If after doing this also, values are not getting applied, we need to see how to debug it.

          • Ismaele Bottelli

            Oke thanks 😀 at this point i insert my login inside the if, right?

          • http://thejackalofjavascript.com/ Arvind Ravulavaru

            Actually, above the if. We force a digest loop to run after your business logic.

          • Ismaele Bottelli

            Awesome! Today i’ll try and i will ask you if work, thanks a lot!!!

  • Junior

    Nothing happens on the device. Moto X

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Hello Junior. What exactly did you try?