Reputation: 77
I'm making a phonegap app in angularJS, and i have a problem with a function inside one of my controllers.
My controller looks like this:
function NavCtrl($scope,navSvc) {
$scope.slidePage = function (path,type) {
navSvc.slidePage(path,type);
};
$scope.back = function () {
navSvc.back();
};
$scope.scan = function(){
console.log('scan(): init');
var scanner = window.cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
if(result.cancelled == 1){
console.log("Scanner cancelado");
}else{
console.log("scanner ok: " + result.text);
$scope.goTo(result.text); // /products/see/result.text
}
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
$scope.goTo= function(barcode){
console.log("Lets go to product " + barcode);
$scope.slidePage('/products/see/'+barcode);
}}
The two first functions are the functions wich made the page transition effects. The Scan function is the one who opens the phonegap barcode scanner plugin (and works right), and the last goTo function is the one wich changes the view.
The behavior desired is that when someone opens the barcode scan, the user gets redirected to the product related to that scan. The strange thing here is that when I scan something, the console log inside the scan function works right (it actually says: Scanner ok: 58746987), but the page change is not made. But, if I open the Barcode again (so I call the scan function again) I see that the console log ("Lets go to product XXX" when XXX is the right barcode scanned before) is fired even if i've not scanned anything the second time, the goTo function gets fired just by calling the function scan.
Is something strange that i've experimented. The functions works right but i need to call the scan twice in order to get the redirect done.
I've also tried by watching a variable inside the scope AND the rootscope, but the behavior is the same.
Any hints? Thank in advance.
Upvotes: 0
Views: 1568
Reputation: 38490
When working like third party libraries like this you need to manually tell Angular that something has changed/happened.
From the documentation:
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.
So replace:
$scope.goTo(result.text);
With:
$scope.$apply(function () {
$scope.goTo(result.text);
});
Upvotes: 1