There seems to be an issue with the functionality of $apply in angular when used in conjunction with form

I've encountered an issue with my code where the form submission doesn't work properly unless I wait a few milliseconds before submitting. The problem seems to be related to setting the value of a hidden field called paymentToken.

My goal is to have the form submit automatically once the paymentToken value is set.

braintree.setup($scope.serverToken, "dropin", {
            container: "dropin-container",
            onPaymentMethodReceived: function (response)
            {
                $scope.paymentToken = 'testing';

                $scope.$apply(function () {
                    $scope.paymentToken = response.nonce;
                    console.log($scope.paymentToken);
                    document.getElementById("myForm").submit(); // The form is submitted, but the paymentToken is not set yet.
                });
            }
        });

Answer №1

Modifying the scope variable ($scope.paymentToken = ...) won't reflect on the user interface (the form being submitted) until after the $scope.$apply function has finished executing.

To ensure that your changes are applied on the next cycle, you should move your submit() function accordingly. One way to achieve this is by:

    console.log($scope.paymentToken);
    $timeout(function() {
        document.getElementById("myForm").submit();
    }, 0);
});

Remember to inject $timeout before using it in your code.

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

The process of setting up React in the terminal becomes tricky when the VS code editor is directing to a non-existent path

Issue with VS Code editor not recognizing existing path Recently attempted to install React using the npx command in the terminal, following steps from various tutorials on YouTube. Despite trying all suggested methods, the installation didn't succee ...

The criteria set by jQuery are met

I have developed my own custom form validation for two inputs: one for a phone number and the other for an email address. Additionally, I have integrated two forms on a single page. Here is a snippet of my code: var email, phone; if (email address passe ...

Download the browser version of UglifyJS 2 now

Is there a way to download the browser version of UglifyJS 2 without having to build it myself? I'm running into issues with the manual installation. I used npm to install uglify-js, but I can't seem to find where to execute the uglifyjs --self ...

After 30 to 80 touches, the movement starts to lag and an error appears in the console

Error Details: [Intervention] A touchend event cancellation attempt was ignored due to cancelable=false, likely because scrolling is in progress and cannot be stopped. preventDefault @ jquery.min.js:2 (anonymous) @ number_grid_game.php:239 each @ ...

Angular routing does not properly update to the child's path

I've organized my project's file structure as follows: app/ (contains all automatically built files) app-routing.module.ts components/ layout/ top/ side/ banner/ pages/ ...

What are some ways to customize the appearance of the Material UI table header?

How can I customize the appearance of Material's UI table header? Perhaps by adding classes using useStyle. <TableHead > <TableRow > <TableCell hover>Dessert (100g serving)</TableCell> ...

What's the best way to integrate Bootstrap into my HTML document?

Hey there, I'm new to the coding world and just started learning. I could use some assistance with including Bootstrap v5.1 in my HTML code. The online course I'm taking is using an older version of Bootstrap, so I'm having trouble finding t ...

The $scope variable is missing from the DOM

I've been trying to implement ng-repeat with AngularJS, but I'm having trouble getting the scope result in my DOM. Is there something wrong that anyone can spot? I've spent hours troubleshooting this and no matter what I do, "players" always ...

Is it possible to utilize the `.apply()` function on the emit method within EventEmitter?

Attempting to accomplish the following task... EventEmitter = require('events').EventEmitter events = new EventEmitter() events.emit.apply(null, ['eventname', 'arg1', 'arg2', 'arg3']) However, it is ...

Tips for effectively modeling data with AngularJS and Firebase: Deciding when to utilize a controller

While creating a project to learn AngularJS and Firebase, I decided to build a replica of ESPN's Streak for the Cash. My motivation behind this was to experience real-time data handling and expand my knowledge. I felt that starting with this project w ...

Should you hold off on moving forward until the asynchronous task finishes?

My goal is to retrieve location coordinates using the Google Maps JavaScript API in an asynchronous manner. Below is the function I've created for this purpose: function fetchCoordinates(address) { var geocoder = new google.maps.Geocoder(); ...

Modifying data on the fly in Angular

I attempted to dynamically modify my data without continuously requesting it from the server. Below is the code snippet I am currently using: $scope.total_earned = () => { //ng-click function from frontend splice(); loadChartData(1); } ...

Is there a way to exit from await Promise.all once any promise has been fulfilled in Chrome version 80?

Seeking the most efficient way to determine which server will respond to a request, I initially attempted sending requests in sequence. However, desiring to expedite this probing process, I revised my code as follows: async function probing(servers) { ...

When I attempted to run `npm start`, an error with status code 1 was thrown,

Upon running npm start, the following error is displayed: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c5d5d6d1d031c031d">[email protected]</a> start /Users/user/Desktop/react-tutorial > react-script ...

Tips for loading a fresh webpage while transferring data from an api

I have a page that displays a list of teams. When a team is clicked, I want to show the title and members of that team on another page. Right now, I have successfully loaded the teams in the list using this code: angular.module('my-app').control ...

The width and height properties in the element's style are not functioning as expected

let divElement = document.createElement("div"); divElement.style.width = 400; divElement.style.height = 400; divElement.style.backgroundColor = "red"; // num : 1 divElement.innerText = "Hello World "; // num : 2 document.body.append(divElement); // Af ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

Issue with the camera functionality in phonegap 3.3.0 API on IOS platform

I am currently in the process of developing an application for iPad that will allow users to capture and store photos. I have encountered some difficulties while using the PhoneGap camera API library, as my code is not generating any errors which makes i ...

Show a caution message when there has been no activity on the page for 3 minutes

I am currently developing a PHP page that includes timed tests. The maximum duration for a test is 1 hour, however the session times out after just 10 minutes of inactivity. Interestingly, when the timeout occurs, the test page does not automatically refre ...

Executing a Component function within an "inline-template" in VueJS

VueJS version 1.9.0 app.js require('./bootstrap'); window.Vue = require('vue'); Vue.component('mapbox', require('./components/mapbox.js')); const app = new Vue({ el: '#app' }); components/mapbox.js ...