How to use Cordova plugins with Ionic Framework, the Angular way

Did Ionic already incorporate support for the (default?) Cordova plugins? And will you ever support them?

For example; I know $ionicPlatform.ready() and / or ionic.Platform support some Cordova stuff but how would I implement those and which Cordova features are available through Ionic?

I need some Network connectivity checking in my app before doing tasks (refresh cached data) and want to use the Cordova Network plugin ‘the Angular way’. I’m now injecting a home-made NetworkService which returns Cordova’s navigator.connection.type but I don’t know if Ionic already supports similar functionality.

Is there some documentation on this? How do you guys use Cordova’s plugins in your Ionic Angular apps?

4 Likes

Ionic doesn’t “support” plugins out of the box. That is, it does not provide an interface to the Plugins. With Cordova, the biggest issue is dealing with the ready event. Ionic manages that.

I simple do this for checking the network connection:

    var checkConnection = function() {

        if(navigator && navigator.connection && navigator.connection.type === 'none') {
            return false;
        }

        return true;
    };

You can put that in your controllers or add it to a service and inject into your controllers. I don’t know of any specific “Ionic” way of doing it.

UPDATE : Of course with plugins that are asynchronous - you’ll need to be sure and use promises or callbacks.

It just doesn’t feel right that way. I don’t know. There also isn’t any fallback logic for the moment Cordova is not available (testing in a browser 9 out of 10 times).

I just came up with this:

'use strict';

/**
* bili.services.cordova Module
*
* General Bili Cordova services module
*/
angular.module('bili.services.cordova')

.service('CordovaNetwork', [function() {
	// Get Cordova's global Connection object or emulate a smilar one
	var Connection = window.Connection || {
		'ETHERNET': 'ETHERNET',
		'WIFI': 'WIFI',
		'CELL_2G': 'CELL_2G',
		'CELL_3G': 'CELL_3G',
		'CELL_4G': 'CELL_4G',
		'CELL': 'CELL',
		'EDGE': 'EDGE',
		'UNKNOWN': 'unknown'
	};

	// Get Cordova's global navigator.connection object or emulate one
	var networkConnection = navigator.connection || {
		type: 'UNKNOWN'
	};

	return {
		isOnline: function () {
			var blnReturn = false;

			switch (this.getStatus()) {
				case Connection.ETHERNET:
				case Connection.WIFI:
				case Connection.CELL_2G:
				case Connection.CELL_3G:
				case Connection.CELL_4G:
				case Connection.CELL:
					blnReturn = true;
					break;
			}

			return blnReturn;
		},

		getStatus: function () {
			return networkConnection.type;
		}
	};
}]);

Bili is the namespace we use internally for cross-project-usable stuff :wink:

2 Likes

I’ve started a project on github called ng-cordova where I’m trying to wrap cordova services in a thoughtful angular way. Any help or feedback is appreciated.

3 Likes

Would you mind posting a link? Sounds like an interesting project and would love to try it out

Nice project @mwball!

Only thing it’s missing in my opinion is fallback support for testing environments that are not run within the Cordova setup (e.g. plugins should simulate behavior when Cordova is not present).

Above, you can find my CordovaNetwork (com.apache.cordova.network-information) service which is fully working with and without Cordova.

I just finalized a similar service for the com.apache.cordova.dialogs plugin, which is working pretty awesome if I may say so :smile:

I created a public Gist on Github to share my progress on this little sideproject with you:

https://gist.github.com/rvanbaalen/9527418

1 Like

Hi @Robin, great idea! Please would you mind posting a sample controller using your services to kind of drive home your gist? Thank you.

@tolu360 Sure, here you go:

angular.module('yourApp', ['bili.services.cordova'])

.controller('AwesomeController', ['$scope', 'CordovaNetwork', 'CordovaDevice', function ($scope, CordovaNetwork, CordovaDevice) {
    
    $scope.refreshBalance = function () {
        if (!CordovaNetwork.isOnline()) {
            CordovaDialog.alert(
                'What have you done with your internet, son?', // Message
                'No Network Connection', // Alert title
                'OK' // Button label
            );
        } else {
            // Do whatever you want when you have internet connection
        }
    }
}]);

I didn’t actually run this code but I hope this gives you an idea on how to use the services.

@Calendee These services or similar once would be an awesome addition to the Ionic Framework. For instance: bower install ionic-cordova-network or bower install ionic-cordova-device

I’m thinking about publishing them to bower myself but I’m a hard-core SVN guy and still need to get used to using GitHub for projects.

2 Likes

Thanks, I’m working on tests and build scripts now. I was thinking about putting each service in it’s own js file ie:
cordova-camera-service.js
cordova-geolocation-service.js

@mwball I like the idea of separating them out, like cordova did with the plugins at the launch of 3.0. Keeps thing modular and prevents carrying the weight of the plugins you don’t want/need.

May want to take a look at these:




and more.

1 Like

Good find @Calendee I came across that repo as well. But last updated almost a year ago and an incomplete (probably non-updated, I suppose it was ‘complete’ a year ago but Cordova has developed since) plugin API didn’t make much sense to me. It’s a good starting point but far from production ready imho.

These are a good start but they don’t use promises, which is what I really was looking for.

I’ll keep working on mine, thanks again for any feedback (or help).

1 Like

Thanks for the heads-up @Robin.

What exactly isn’t using promises? My services are…

No I was talking about the other repos that were linked to above.

1 Like

My bad :wink: I thought you were missing something. But indeed; these repo’s are both outdated and are missing fully implemented promises.

@mwball If you can use anything from my Gist in your repository, please feel free to copy/paste it.

Thanks, I like how you do the graceful failure. I was going to detect if I was in a webview and inject a different set of services depending.

Thanks @mwball. My main goal with these services was to

  1. Be able to use the Cordova plugins, the Angular way
  2. Be able to use the Cordova plugins in the first place. Without having to simulate my app every time in Ripple or even an emulator.

That’s where the graceful failure handing comes from. I’m personally not interested in fallback functionalities: It’s Cordova or ‘fake Cordova’ for me :smile:

I agree, it’s fake or real.

You can see the snippet I use here to decide which set of services to inject:

1 Like