Search code examples
javascriptangularjscordovaphonegap-pluginscordova-plugins

Calling phonegap plugin from AngularJS controller


I have a 3rd party barcode scanner plugin. I need to call this plugin from an angularJS controller. I am able to successfully trigger the scanner on deviceready event from the index.js which comes with a basic phonegap project. However, when I try to call the plugin from the controller, the scanner plugin is not triggered. Below you can find my index.js code:

onDeviceReady: function() {
        app.receivedEvent('deviceready');
        cordova.plugins.pdf417Scanner.scan(function callback(scanningResult){
            //handle success callback
        }, function errorHandler(err){
           //handle error
        }, arg1, arg2
       );
}

When I try to do this in the angular controller, something like:

var myApp = angular.module("scanApp",[]);
myApp.controller("mainCtrl", function(){
     document.addEventListener('deviceready', fireScanner, false);
     function fireScanner(){
          alert("fireScanner is on");
          cordova.plugins.pdf417Scanner.scan(function callback(scanningResult){
           //handle success callback
        }, function errorHandler(err){
           //handle error
        }, arg1, arg2
       );
     }

Now, in the angular controller, I am wrapping the plugin call in a deviceready event listener. The alert saying "fireScanner is on" is getting triggered but the barcode scanner plugin is not getting triggered. I am sure I am missing something simple but I am not able to figure out what. Any help would be much appreciated!


Solution

  • I found out what the issue was! It was with the arguments I was passing to the plugin! In index.js, I was creating arg1 and arg2 under onDeviceReady function and it was not making itself available outside the onDeviceReady function. I had not created the arg1 and arg2 in the controller and it was simply not available in the controller and hence the plugin was not being triggered. I had to define arg1 and arg2 in controller to make it work.