DIY ng* Wrappers for Cordova plugins

Whilst getting to grips with the Ionic framework, I came across an issue where Cordova plugins are not readily available in AngularJS components (controllers / services). To remedy this, there is the ngCordova project ( which currently lists 63+ Cordova plugins for which they provide AngularJS wrappers.

However, the only plugin that ngCordova includes for dealing with preferences (‘$cordovaPreferences’) will only work with Apple iOS, whereas I need something that covers iOS, Android and (what seems to be the poor-relation of the mobile world) Windows Phone 8.

Although there are other Cordova plugins out there (in particular as I mentioned at the start, the plugins are not readily available in AngularJS components.

In order to get this working, the first step is to install the Cordova plugin as normal via:

Once the plugin is installed, I checked the plugin’s www/JS file for the function definitions I wanted to wrap. In this instance the only functions were ‘fetch’ and ‘store’.

To keep things tidy and in one place, I decided to add the new factory to the existing ngCordova.js file (this IS going to be an ngCordova-style wrapper after all).

I am also going to re-use the existing ‘ngCordova.plugins.’ namespace for the module, and stick with the ‘$cordova…’ prefix for the factory name. This means my skeleton factory will look like this:

Since this is going to be a simple wrapper, I am also going to copy the parameter lists for the ‘fetch’ and ‘store’ functions from the main Cordova plugin JS file.

Once I have the functions in place, and I know the parameter list I can start passing through the calls to the main plugin methods like so:

Finally if you open the /www/lib/ngCordova/ngCordova.js file and go to line 4381(-ish) you will see all the existing ngCordova dependencies. You will need to add the newly-created ‘ngCordova.plugins.AppPreferences’ to this list.

Congrats! You have just created a new ngCordova wrapper.

In this example, I have used a basic Cordova plugin which uses callback functions as parameters to signify the success or failure of the function call. It is more than likely that you will come across Cordova plugins which use promise.resolve / reject instead of callbacks. In this instance you can simply inject $q into your wrapper definition and wrap the promise returned by the Cordova plugin and listen for the resolve / reject.

– Jonathan