srv
srv

Reputation: 440

AngularJS http post and redirect to payment gateway

In AngularJS, I want to post a set of data and get redirect to a payment url. I have added the following function and a directive to achieve this.

However I can't achieve the same and got following two errors $interpolate:interr and TypeError: element.submit is not a function error.

How to solve the error reported by AngularJS? I am novice with AngularJS, so couldn't understand whats happening.

$scope.transaction = function () {
    var data = $scope.details;
    var formData = {
        redirectUrl: 'https://payment-gateway-url',
        redirectMethod: 'POST',
        redirectData: {
            id: data.id,
            para1: data.para1
        }
    };
    $rootScope.$broadcast('gateway.redirect', formData);
    $scope.$emit('gateway.redirect');
};

app.directive('autoSubmitForm', ['$timeout', function($timeout) {
    return {
        replace: true,
        scope: {},
        template: '<form action="{{formData.redirectUrl}}" method="{{formData.redirectMethod}}">' +
            '<div><input name="{{key}}" type="hidden" value="{{val}}" /></div>' +
            '</form>',
        link: function($scope, element, $attrs) {
            $scope.$on($attrs['event'], function(event, data) {
                $scope.formData = data;
                console.log('redirecting now!');
                $timeout(function() {
                    element.submit();
                })
             })
        }
    }
}]);

<div auto-submit-form event="gateway.redirect"></div>

Upvotes: 1

Views: 2891

Answers (1)

Francisco Carmona
Francisco Carmona

Reputation: 1701

The problem is that the directive is not interpolating the values of action, method, name and value in the template. And the element is referring to the div where the directive is defined, so element is not really the form. You can try it in the way I show you in the plunker. I generate the form dynamically and at the end I submit it with jQuery.

app.directive('autoSubmitForm', ['$interpolate', function($interpolate) {
  return {
    replace: true,
    scope: {
      formData: '='
    },
    template: '',
    link: function($scope, element, $attrs) {
      $scope.$on($attrs['event'], function(event, data) {
        var form = $interpolate('<form action="{{formData.redirectUrl}}" method="{{formData.redirectMethod}}"><div><input name="id" type="text" type="hidden" value="{{formData.redirectData.id}}"/></div></form>')($scope);
        console.log(form);
        jQuery(form).appendTo('body').submit();
      })
    }
  }
}]);

https://plnkr.co/edit/OUu9XgtMttPCri3KvapJ?p=preview

Hope it helps!

Upvotes: 2

Related Questions