We’re going to see how to build a Barcode Scanner for Android and IOS application using Ionic, Angular and Cordova plugin BarcodeScanner which has the ability to scan barcodes in the following formats:
- QR Code
- Data Matrix
- UPC E
- UPC A
- EAN 8
- EAN 13
- Code 128
- Code 39
Pretty much all the formats anyone would ever need. The plugin itself makes use of the very popular ZXing library.
To implement the barcode scanner in our Android and iOS application, lets start by creating a new Ionic Framework project.
Creating a New Ionic Project
To make things as easiest as possible to understand, we’re going to start with a fresh project ‘Blank’.
Using the Command Prompt (Windows) or Terminal(Mac and Linux), execute the following in your workspace directory:
ionic start BarcodeScanner blank cd BarcodeScanner ionic platform add android ionic platform add ios
Remember, if you’re not using a Mac, you cannot add and build for the iOS platform.
The next thing we want to do is add the barcode scanner plugin into our project. This can be done by doing the following from a command line:
Now technically you can continue to build your application with just the plugin, but we are going to install the AngularJS ngCordova extension set to make our lives a little easier.
Start by downloading the latest ngCordova release and copying the ng-cordova.min.js file into your project’s www/js directory.
To add the extension set into our application we must first include the script before the cordova.js line in our index.html file. It will look something like this:
With your index.html file set up, now we need to add the extension set to our app.js file. After your angular.module line to look something like the following:
It is now time to work some programming magic. Create a controller and include the following method to initialize the barcode scanner. For this example, I did the following:
You’ll notice that we had to include $cordovaBarcodeScanner in our controller. The scanner returns an AngularJS promise, so if there is an error or success we’ll know about it.
Just like that, you’ve got a very simple barcode scanner in your Ionic Framework application.