Search code examples
angularjsionic-frameworkcordova-plugins

Barcode scanner plugin returns Reference error


I'm trying to call a barcode scan function on button click but it returns the following error:

ReferenceError: cordova is not defined
at ChildScope.$scope.scanBarcode (controllers.js:10)
at fn (eval at compile (ionic.bundle.js:27643), <anonymous>:4:224)
at ionic.bundle.js:65429
at ChildScope.$eval (ionic.bundle.js:30400)
at ChildScope.$apply (ionic.bundle.js:30500)
at HTMLButtonElement.<anonymous> (ionic.bundle.js:65428)
at defaultHandlerWrapper (ionic.bundle.js:16792)
at HTMLButtonElement.eventHandler (ionic.bundle.js:16780)
at triggerMouseEvent (ionic.bundle.js:2953)
at tapClick (ionic.bundle.js:2942)

here's my code for controller.js:

angular.module('app.controllers', ['ionic', 'ngCordova'])
.controller('page4Ctrl', ['$scope', '$stateParams', '$cordovaBarcodeScanner',function ($scope, $stateParams, $cordovaBarcodeScanner) {
$scope.scanBarcode = function()
{
     cordova.plugins.barcodeScanner.scan().then(function(imageData) {
        alert(imageData.text);
        console.log("Barcode Format -> " + imageData.format);
        console.log("Cancelled -> " + imageData.cancelled);
    }, function(error) {
        console.log("An error happened -> " + error);
    });
};

}])

and here's the code for inserting cordova/ngcordova in index.html before calling app.js:

<script src="lib/ionic/js/ionic.bundle.js"></script>

<script src="cordova.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>

what could be the problem?


Solution

  • You will have to change implementation for barcode scanner as

    $scope.scanBarcode = function(){
        $cordovaBarcodeScanner.scan().then(function(imageData) {
            alert(imageData.text);
            console.log("Barcode Format -> " + imageData.format);
            console.log("Cancelled -> " + imageData.cancelled);
        }, function(error) {
            console.log("An error happened -> " + error);
        });
    };
    

    As you have injected $cordovaBarcodeScanner in controller. cordova.plugins.barcodeScanner will not be available to access directly.

    Ref. : http://ngcordova.com/docs/plugins/barcodeScanner/

    Regards.