Return of ionic barcode scanner in factory service, undefined


#1

Hi, I’m building with Ionic framework.
I need to use the QR scan code. After the scanner of QR code, I need to
select a substring of the return string by the scanner. I want to put
the QR scan code inside the factory service, but I have the problem with
the return variable in controller of Angular js. This return a
undefined variable.
the factory code I create is this:

app.factory(“qrCodeService”,[’$cordovaBarcodeScanner’,’$ionicPlatform’,
function(barcodeScanner , ionicPlatform){
var _id = function(){
var p = ionicPlatform.ready(function(){
var cod = barcodeScanner.scan()
.then(function(imageData){
var _link = imageData.text;
var _pos_slash = _link.lastIndexOf(’/’);
return _link.substr(_pos_slash+1);
})
.catch(function(err){ return “0000000”; });

                         return cod;
                        }); 
                     return p;
                 };
                return{
                    getId : _id
                }     

}]);

the controller that i build is this:

app.controller(“indexCtrl”,[’$scope’,’$http’,
function ( scope , http ){

scope.codeScanner=function(){
   var  id = qrCodeService.getId();
    alert(id); /*this return undefined*/
}

}

Some of you have a good advice to find a better quality solution?


#2

you are calling async code --> promises (.then, .catch). So the id is not set, if you call qrCodeService.getId() in the controller.

You should move the whole scanning functionality in a service function you call.


#3

Thanks bengtler,
but I can’t understand how I can return the id parameter to My controller.js (I need the id information in my controller…)…