0

I'm hoping to use paypal and angularJS, I came across an awesome angularjs directive for paypal

<paypal-button business="[email protected]" language-code="en_US" currency-code="USD"
    item-name="socks" amount="{{dollarValue}}" ng-model="paypalButton"></paypal-button>

The problem I'm having here is the amount for the button is passed via scope

Say the user wants 10 socks, each sock is $5, the user enters "10", a back end script multiplies 10x5 and returns 50 as the number that should go in the amount=""

how to I pass $scope.amount to be the amount submitted on the paypal form?

I've tried to see if I can pass amount to the paypal directive, but I'm having trouble passing it to the directive.

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 = [ // PayPal allowed language codes
          'en_US',
          'es_ES',
          'fr_FR',
          'it_IT',
          'de_DE'
        ];
        var currencyCodes = [ // PayPal allowed currency codes
          'AUD',
          'CAD',
          'CZK',
          'DKK',
          'EUR',
          'HKD',
          'HUF',
          'ILS',
          'JPY',
          'MXN',
          'NOK',
          'NZD',
          'PHP',
          'PLN',
          'GBP',
          'RUB',
          'SGD',
          'SEK',
          'CHF',
          'TWD',
          'THB',
          'USD'
        ];
        var buttonSizes = [ // PayPal allowed button sizes
          'SM', // small
          'LG' // large
        ];
        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);
      }
    };
  });
4
  • Wouldn't you just use amount="{{amount}}"? Commented Feb 16, 2015 at 1:36
  • tried that doesn't work Commented Feb 16, 2015 at 2:12
  • can you clarify on why amount="{{amount}}" doesn't work? does it pass the wrong value? does it pass nothing at all? does it throw an error? Commented Feb 16, 2015 at 2:17
  • check this out, try changing amount:'=' to amount: '@'. Otherwise, use the double braces in the attribute value (which you use in the directive depends on if you only need the string value, or need to setup 2-way data binding between directive and parent scope). Commented Feb 17, 2015 at 5:16

1 Answer 1

0

I'm seen a lot of folks searching for a paypal and angularjs option... here's what I did to get it all working using the code from the help I got here render <script> tag in angularjs

from the controller I broadcast the paypal amount

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

using the provided directive I listen for the broadcast and update 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)

                    }
                );

    }
};
}]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.