Thursday, 23 October 2014

Adding ngCordova Plugin to Visual Studio Cordova Project

We will see how to add a plugin from ngCordova which has a collection of Cordova API plugins wrapped in AngularJS. ngCordova will help even more Cordova developers who are using AngularJS.

1. First, include ng-cordova.js or ng-cordova.min.js file into our project structure. We can use bower to install that or download the zip file from its GitHub repository then find the js file inside.

2. On our project main page, add a reference to it before the reference to cordova.js file.
<script src="some_path/ng-cordova.min.js"></script>
<script src="cordova.js"></script>

3. Include 'ngCordova' in our app module. For example:
var myApp = angular.module('myApp', ['ngCordova', . . .]);

4. Add the intended plugin wrapped by <vs:feature></vs:feature> inside <vs:features> node in our project config.xml file like below:
<vs:features>
  <vs:feature>plugin_id@version_number</vs:feature>
  <vs:feature>plugin_2_id@version_number</vs:feature>
  . . .
</vs:features>
Right click config.xml file then select View Code to do this.

To find the plugin Id and version number, we can check from plugins.cordova.io site or from the plugin.xml file on the plugin repository site. However if we are getting the information from plugin.xml file, that will always be the latest version which sometimes is not the stable one.

An example for the latter one, say we would like to use Local Notification plugin. Go to its site https://github.com/katzer/cordova-plugin-local-notifications then open plugin.xml file located on the root. Inside the plugin element there are 'id' and 'version' attributes.

When building the project, Visual Studio will download the plugin and add to the project if it has not done so.


5. Inject the plugin service into our controller then we can start using it.
For example, to use Local Notification, we need to inject $cordovaLocalNotification like this:
myApp.controller('MyCtrl', ['$cordovaLocalNotification', . . . ,
  function ($cordovaLocalNotification, . . .) {
  . . .
}]);

No comments: