Phonegap app: The function in the AngularJS controller is only executed when called twice

I am currently developing a phonegap app using angularJS, and I have encountered an issue with a function in one of my controllers.

Here is how my controller looks like:

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 first two functions handle the page transition effects. The Scan function triggers the phonegap barcode scanner plugin successfully, and the last goTo function changes the view accordingly.

The desired behavior is that when a user opens the barcode scan, they should be redirected to the corresponding product. The issue arises when, upon scanning something, the console log inside the scan function displays correctly (e.g., Scanner ok: 58746987), but the page does not change. Surprisingly, upon reopening the Barcode scan, even without scanning anything a second time, the console log ("Lets go to product XXX" where XXX is the correct barcode scanned previously) is triggered automatically, causing the goTo function to execute without another scan being performed.

This unexpected behavior has puzzled me. Despite trying to monitor variables within both the scope and the rootscope, the problem persists.

Any insights or suggestions would be greatly appreciated. Thank you in advance.

Answer №1

When utilizing third-party libraries in Angular, it is important to manually notify Angular when a change or event occurs.

As stated in the documentation:

The $apply() function is employed to run an expression in Angular from external sources such as browser DOM events, setTimeout, XHR, or third-party libraries. Since we are interacting with the Angular framework externally, it is required to follow proper scope lifecycle and exception handling processes.

Instead of using:

$scope.goTo(result.text);

Use:

$scope.$apply(function () {
    $scope.goTo(result.text);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I adjust the size of the renderer in Three.js to fit the screen?

Encountering issues with the code snippet below: //WebGL renderer renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); //TODO: set optimal size document.body.appendChild(renderer ...

Alter the content of a div depending on the values of three different elements

Hello everyone, I am new to the world of jQuery and javascript, and I am facing a challenge that I need some help with. Within a form, there are two fields that I would like to perform calculations on. Here is what I have attempted so far: jQuery.fn.calcu ...

Tips for updating HTML Ajax content when the back button is clicked

I created a search page with filters that update the URL parameters to prevent values from being lost if the page is refreshed. q = $('#form input[name=q]').val(), srchtype= $('#filter input[name=srchtype]:checked').val(), sortBy ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

What is the solution for handling nested promises in Node.js?

I am currently using the node-fetch module for making API calls. I have a function that handles all the API requests and returns both the status code and the response body. The issue I'm facing is that when returning an object with the response data, ...

Experience the power of dynamic site regeneration with GatsbyJS

Currently, I am working on a website built in GatsbyJS that deals with large datasets of dynamic content fetched using React fetch upon page load. The challenge here is to display semi-live data that updates every 5 minutes. I am curious about how I can m ...

What is the best way to create a line graph with D3.js in order to display data that is obtained from a server-side source?

I am trying to access data from a server side link, which is as follows: The data I want to retrieve is in JSON format and looks like this: {"Id":466,"Name":"korea", "Occurren ...

Tips for navigating through pagination indexes with Angular 6

Hey there, I'm currently working on a project where I need to automatically click through each pagination index. Initially, only the first index can be clicked. After that, the following page indexes are not clickable. Here's the code snippet: ...

The issue of AngularJS inline style color not functioning in Internet Explorer 11 has been identified

Hello, I am currently attempting to dynamically change the color of a p tag. However, I am facing issues with IE-11 not supporting this functionality. How can I resolve this problem? <p style="color:{{userData.color}} !important;">{{userData.someTex ...

Explanation of JavaScript code snippet

fnTest = /abc/.test(function () { abc; }) ? /\bchild\b/ : /.*/; I am struggling to comprehend the functionality of this particular javascript snippet. Would someone be able to elaborate on the logic behind this code fragment? ...

Executing Parent function in Reactjs (Triggering Drawer when menu item is clicked using Material-ui)

I'm having some trouble trying to activate the drawer when a user clicks on a menu item. Unfortunately, my current solution is not working as expected. Can anyone provide assistance? Parent import React, { Component } from 'react'; // Impo ...

Mongoose schema nesting guide

I've encountered an issue while attempting to nest schemas in mongoose, and unfortunately I'm struggling to pinpoint the exact cause. Here's what my current setup looks like. Starting with the parent schema: const Comment = require("./Comm ...

Why isn't my file being recognized post-multer middleware?

I am currently facing an issue with uploading a filename and a post (similar to 9GAG style) to my MySQL database, and storing the file in my project folder. The front end is able to retrieve the file without any problems (verified through console.log), but ...

The React Apexchart fails to correctly adjust its height based on its parent container when set to 100%

Currently, I am working with react-apexcharts and facing an issue where I am trying to set the height of the chart to be 100% of its parent element. However, instead of taking the height from its parent, it is only showing a minimum height of 445px. Even a ...

Executing a function from a parent controller within its own context

I am facing an issue where I want the parent controller's function getDataInParent to be called within the context of the parent's controller itself. For example: The child directive is correctly configured like this within the parent directive ...

What is the process for creating a folder using Firebase Cloud Functions with Storage?

How do I create a folder named "posts"? Storage bucket path --> gs://app.appspot.com/posts Code to generate thumbnail from storage object exports.generateThumbnail = functions.storage.object() .onChange(event => { const object = event.data ...

Retrieve the parameter value from a directive within a controller

Looking to implement a directive and utilize the argument in your controller? <body ng-app="tstApp"> <navigationbar tst="hello"> </navigationbar> </body> To achieve this, you will need to create a directive along with its ...

What is the method to establish a reference based on a value in programming?

Having some trouble setting the 'ref' of a TextInput from a value. Here's an example: var testtest = 'testvalue' <TextInput ref=testtest autoCapitalize="none" autoCorrect={false} autoFocus={false} placeholderTextColor="#b8b8b ...

Add a user to a guild using Discord API

Hello, I'm currently working on integrating the Discord API to automatically add users to a guild upon login. However, I keep encountering a 401 Unauthorized error and I'm unsure of the reason behind it. Below is a snippet of my code: const data ...

The accordion feature fails to function properly when incorporated into an ajax response

When I click a button, an Ajax response is loaded. The response is successfully appended where it should be, but the issue arises with the accordion not working for the response part. Below is the structure of my response: <div class="articles-content ...