Barcode Scanning Using Ionic Framework and Cordova (PhoneGap)

I recently found myself needing to scan barcode in one of my applications I was developing for a customer. I needed to scan QR code that was generated on screen and while doing some research I decided to use open source project ngCordova. ngCordova is basically a set of Apache Cordova (aka PhoneGap) plugins ready to use in AngularJS project. Their BarcodeScanner functionality supports reading many types of barcodes, including the one I needed. It supports all the mobile platforms I was targeting (Android, iOS and Windows Phone).

While the use of BarcodeScanner is really simple using plain vanilla Javascript:
      function (result) {
          alert("We got a barcode\n" +
                "Result: " + result.text + "\n" +
                "Format: " + result.format + "\n" +
                "Cancelled: " + result.cancelled);
      function (error) {
          alert("Scanning failed: " + error);
usage in Ionic framework under AngularJS is a little more interesting. Include the ngCordova and Cordova library in your Index.html file:
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
        <script src="lib/ionic/js/ionic.bundle.js"></script>
        <script src="js/ng-cordova.min.js"></script>
        <script src="cordova.js"></script>
        <script src="js/app.js"></script>
    <body ng-app="starter">
After you have set index.html, open app.js and register module with something like angular.module('starter',['ionic', 'ngCordova']) Then include $cordovaBarcodeScanner in the controller and use the library as in the sample below:
exampleApp.controller("ExampleController", function($scope, $cordovaBarcodeScanner) {
    $scope.scanBarcode = function() {
        $cordovaBarcodeScanner.scan().then(function(imageData) {
            console.log("Barcode Format -> " + imageData.format);
            console.log("Cancelled -> " + imageData.cancelled);
        }, function(error) {
            console.log("An error happened -> " + error);
Do not forget to include $cordovaBarcodeScanner in the definition of the controller.

1 comment:

  1. excuse works for android 6 this pulling,
    I have a problem with access to the camera, the error says that android has trouble accessing the camera, rinicie your device.