Transfer monetary value to AngularJS PayPal directive

I'm interested in integrating PayPal with AngularJS, and I recently found an amazing AngularJS directive for PayPal.

<paypal-button business="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f6e6d5f8f0bbf6faf8">[email protected]</a>" language-code="en_US" currency-code="USD"
    item-name="socks" amount="{{dollarValue}}" ng-model="paypalButton"></paypal-button>

The issue I'm facing is that the amount for the button needs to be passed via scope.

For example, if a user wants to purchase 10 socks priced at $5 each, they will enter "10". A backend script then calculates 10 x $5 to return 50 as the amount value that should be placed in the amount="" field.

How can I pass $scope.amount as the submitted amount on the PayPal form?

I attempted to pass the amount to the PayPal directive but encountered difficulties in doing so.

angular.module('WCtrl', [])
.controller('WController',['$scope','$q','$http','$location','$interval','$firebase','$timeout','$stateParams','$routeParams', function($scope,$q,$http,$location,$interval,$firebase,$timeout,$stateParams,$routeParams) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

/$scope.calculate = function(){
    //console.log("reached")
    $scope.calculate = $scope.calc();
    $scope.calculate = $scope.calculate.then(function(amount){

    $http.post('public/views/calculate.php?a='+amount,$.param($scope.FormData))
        .success(function(response){
            if(!response.success){

                $("#message").attr('class','alert alert-danger text-center')
                $scope.message = response.message
            }else{


                    $scope.amount = response.amount

            }
        })

    })
}


}])

.directive('paypalButton',function() {
    return {
      restrict: 'E',
      scope: {
        amount:'='
      },
      link: function(scope, element, attrs){    
           element.text(scope.amount);    
        },  
      compile: function(element, attrs) {
        var languageCodes = [ 
          'en_US',
          'es_ES',
          'fr_FR',
          'it_IT',
          'de_DE'
        ];
        var currencyCodes = [ 
          'AUD',
          'CAD',
          'CZK',
          'DKK',
          'EUR',
          'HKD',
          'HUF',
          'ILS',
          'JPY',
          'MXN',
          'NOK',
          'NZD',
          'PHP',
          'PLN',
          'GBP',
          'RUB',
          'SGD',
          'SEK',
          'CHF',
          'TWD',
          'THB',
          'USD'
        ];
        var buttonSizes = [ 
          'SM', 
          'LG' 
        ];
        var name = this.name;
        function err(reason) {
          element.replaceWith('<span style="background-color:red; color:black; padding:.5em;">' + name + ': ' + reason + '</span>');
          console.log(element.context);
        }
        var action = attrs.action || 'https://www.paypal.com/us/cgi-bin/webscr';
        var business = attrs.business;
        var languageCode = attrs.languageCode || 'en_US';
        var currencyCode = attrs.currencyCode || 'USD';
        var itemName = attrs.itemName;
        var amount = parseFloat(attrs.amount);
        var buttonSize = attrs.buttonSize || 'SM';
        var imgAlt = attrs.imgAlt || 'Make payments with PayPal - it\'s fast, free and secure!';
        if (!business) { return err('business not specified!'); }
        if (!itemName) { return err('item name not specified!'); }
        if (!amount) { return err('amount not specified!'); }
        if (isNaN(amount)) { return err('amount is not a number!'); }
        if (languageCodes.indexOf(languageCode) < 0) { return err('unforeseen language code!'); }
        if (currencyCodes.indexOf(currencyCode) < 0) { return err('unforeseen currency code!'); }
        if (buttonSizes.indexOf(buttonSize) < 0) { return err('unforeseen button size!'); }
        var imgSrc = 'http://www.paypalobjects.com/' + languageCode + '/i/btn/btn_buynow_' + buttonSize + '.gif';
        var template =
          '<form name="_xclick" action="' + action + '" method="post">' +
          '<input type="hidden" name="cmd" value="_xclick">' +
          '<input type="hidden" name="business" value="' + business + '">' +
          '<input type="hidden" name="currency_code" value="' + currencyCode + '">' +
          '<input type="hidden" name="item_name" value="' + itemName + '">' +
          '<input type="hidden" name="amount" value="' + amount + '">' +
          '<input type="image" src="' + imgSrc + '" border="0" name="submit" alt="' + imgAlt + '">' +
          '</form>';
        //element.replaceWith(template);
        element.append(template);
      }
    };
  });

Answer ā„–1

I have noticed many individuals looking for a paypal and angularjs solution... here is the approach I took to successfully make it work by utilizing the code I received assistance with on how to render <script> tag in angularjs

Within the controller, I broadcasted the paypal amount

$scope.$broadcast("paypalAmount", $scope.dollarValue)

By using the provided directive, I monitored the broadcast and updated the amount for the payment button

.directive('paypal', [function(){
return {
    scope: {},
    link: function($scope, element, iAttrs) {

                $scope.$on(
                    "paypalAmount",
                    function handlePingEvent( event, dollarValue ) {

                        var scriptElem = angular.element(document.createElement('script'))
                        scriptElem.attr({src:'https://www.paypalobjects.com/js/external/paypal-button.min.js?merchant=YOUR-PAYPAL-EMAIL','data-button':'buynow','data-name':'Arcade Tokens','data-amount':dollarValue,'data-currency':'USD','data-callback':'https://gamerholic.com/ipn/data.php' }) // set var appropriately
                        element.append(scriptElem)

                    }
                );

    }
};
}]);

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

Issues with image uploads in Node.js database storage

Trying to update an image using the put method is resulting in a 'filename' undefined error. Interestingly, the image updates successfully when editing without changing the image. The code snippet below shows the implementation: app.put('/a ...

Promise rejection not caught: ; Zone: angular ; Task:

While using meteor and trying to set up a (click) attribute, I encountered the following error message. https://i.sstatic.net/Qzk9T.png This is my code: import { Component, NgZone, AfterContentInit } from 'angular2/core'; import { NgIf, NgFor ...

When a user accesses a page, the UI-router shows the raw code in the UI-views

I am a newcomer to utilizing ui-router and I am facing challenges with managing routing and reloading some states. Any assistance would be greatly appreciated. An overview of my index.html <html ng-app="resApp"> <head></head> < ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

Tips for properly setting and accessing data objects in React when utilizing a Firebase database

Iā€™m encountering issues with storing and retrieving data using the useState hook in React after fetching it from a Firebase database. The issue appears to be related to not all users having all values in the playerData data packet ā€“ for example, if a p ...

The analytics event code is visible in the source code, but is not displaying in the console

I am facing an issue with a website built on Umbraco and it has me completely stumped. I have set up event tracking for Analytics on several download buttons, and while most of them are functioning properly, there is one button causing me trouble. When I ...

Problems with the functionality of the remote feature in Twitter Bootstrap Modal

Utilizing Twitter Bootstrap, I aim to retrieve HTML from another page and inject it into the modal on my current page. This led me to create a JavaScript function to facilitate this process. Within my 'index.php' file, I include the following: ...

Encountering Difficulty Accessing Index.ejs with Express.js

Currently, I am enrolled in a Linkedin course that focuses on building websites using express.js. I have encountered an issue where my index.ejs page is not rendering properly, as the server keeps loading my index.html page instead. I have tried searching ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

Start up AngularJS service - factory when the document is fully loaded

Apologies for the novice query, but I am new to AngularJS and OnsenUI. I have a service set up to retrieve data from SQLite: module.factory('$update', function () { var update = {}; db.transaction(function (tx) { tx.executeSql(& ...

Troublesome problems with AngularJS forms

Having trouble making a form work with angularjs. Encountering this error: {"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x9bd4f8c>, 'ht ...

JavaScript failing to load following PHP header() redirect

I've set up a page that allows users to sign in by filling out a basic form, which then sends the data to a separate PHP script for validation. After the validation process is complete, the PHP script uses the header() function to redirect the user to ...

Encountered an issue while trying to create a new controller in Angular, where the error indicated

Apologies for any language errors in advance. I recently delved into angular using the MEAN stack (MongoDB, Express, Angular, Node) and encountered an issue. Every time I try to create a simple Controller, I keep getting this error: Argument 'test ...

Utilizing destructuring and Object.entries for advanced formatting

I'm embarking on a new React project and facing an issue with the JSON data structure returned by my API for meetings. I attempted to utilize destructuring and Object.entries. This is what I currently have: { "meetings": [ ...

I want to trigger the opening and closing of an accordion by clicking on an arrow

I am encountering an issue with the Material UI accordion. When I click on the arrow, the accordion opens but clicking again does not close it. I would like to make it so that when the user clicks on the arrow, the accordion will toggle between open and cl ...

Stop the occurrence of rapid double clicking on a link button within a Repeater control

When I try to fast double click, the JavaScript function Show() gets called (displaying "please wait"), but Button_Click in vb.net does not get called. Any suggestions on how I can solve this issue? Here is my code snippet: ASPX <ItemTempla ...

Cover the <img ...> tag in HTML using JavaScript

I'm currently working on creating a simple game involving sliding ice-blocks. I ran into an issue while testing this JSFiddle and I'm looking to "hide" the image/button triggered by the line alert('Game starts!');. I attempted using sta ...

The redirection of the URL after form submission is not functioning correctly

I'm attempting to develop a pair of dropdown lists in Elementor where the second dropdown's options depend on what is selected in the first, and the second contains URLs linked to a GO button that redirects to the chosen URL. However, I've f ...

Tips for refining search outcomes from web scraping with Google App Script

My objective is to scrape data from the website : I am specifically interested in extracting the SP500 PE number, which currently stands at 39.57 (at the time of writing). I require this number to be formatted as 39,57, rather than 39.57. This is my curr ...

Encountering a JavaScript error due to an erroneous character when trying to parse

I need to convert a `json` string into an object format that is extracted from a `.js` file. Here is the `JSON` string located in `document.js`: [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, ...