【问题标题】:Passing AngularJS $scope data to Jquery element (Stripe Checkout)将 AngularJS $scope 数据传递给 Jquery 元素(Stripe Checkout)
【发布时间】:2014-03-09 11:05:11
【问题描述】:

我正在尝试将使用 Jquery 构建的 Stripe Checkout 集成到使用 Angular 构建的 SPA 中。我想使用自定义版本,并能够根据当前范围更改金额或电子邮件等数据。

我尝试过写一个指令:

.directive('ngSparkline', function() {
  return {
    restrict: 'E',
    scope: {
      amount: '@'
    },
    templateUrl: 'views/stripe.html',
    replace: true
  };
});

根据 Stripe 的文档,其中 stripe.html 包含以下 sn-p:

<button id="customButton">Purchase</button>

<script>
      var handler = StripeCheckout.configure({
        key: "pk_test_sK21onMmCuKNuoY7pbml8z3Q",
        image: "apple-touch-icon.png",
        token: function(token, args) {
          jQuery.ajax({
            type:"POST",
            url: "/stripetoken/", //For own custom domain, put the full https appspot url here
            data:  token,
            timeout: 200000,
            beforeSend: function(settings) {
              console.log("About to send the transaction, may take a while, but this will be async")
            },
            success: function(result)
            {
              alert("Paiement Effectué");
            },
            error: function(result) {
              console.log("Error",result);
            }
          });
        }
      });

      document.getElementById("customButton").addEventListener("click", function(e) {
        // Open Checkout with further options
        handler.open({
          name: "Vinify",
          description: "Recharge Vinibar",
          currency: "EUR",
          panelLabel: "Payer",
          amount: {{amount}}
        });
        e.preventDefault();
      });
    </script>

但结帐不会触发,即使我只是尝试使用硬写的随机数量。当我将相同的 sn-p 直接放在我的 html 中时,将 {{amount}} 替换为随机数量,它工作正常。

最好的方法是什么?我想用 checkout 是因为 UI 已经建好了,重写会有点痛苦。我尝试过 angular-payments,但代码与我使用的 ionic 框架混淆了。

谢谢!

【问题讨论】:

  • 我绝对不会在 &lt;script&gt; 标签中放置 Angular 绑定...
  • 是的,我知道这感觉很奇怪。但它适用于更简单的 javascript sn-p。不是 Jquery 的东西。
  • 我认为这会导致浏览器在每次更改绑定值时重新编译并重新执行&lt;script&gt;标签的全部内容。

标签: jquery angularjs angularjs-directive stripe-payments


【解决方案1】:

我会将本示例中的所有 StripeCheckout 内容放在 ngSparkline 指令的链接部分中,并在 DOM 中像这样引用它:

<button ng-spark-line>Purchase</button>

在您的链接部分,不要使用元素 id 来绑定点击事件,而是这样做:

      $element.bind('click',function(e) {
        // Open Checkout with further options
        handler.open({
          name: "Vinify",
          description: "Recharge Vinibar",
          currency: "EUR",
          panelLabel: "Payer",
          amount: $scope.amount
        });
        e.preventDefault();
      });

【讨论】:

  • 谢谢!我有一种感觉,这将是一种方式,但以前从未使用过链接功能。我将链接函数声明为:link: function(scope, element, attrs),所以我使用elementscope 而不是$element$scope。我看到它在各种例子中都是这样声明的。这是正确的方法吗?
  • 没有正确的方法——我只是更喜欢在我的代码中使用“$”来描述这些是 Angular 对象
猜你喜欢
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2021-01-24
  • 2022-08-23
  • 2015-05-16
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
相关资源
最近更新 更多