我正在尝试将 paypal 的支付按钮添加到我的 angularjs 应用程序中,
$scope.paypal ='<script async="async" src="https://www.paypalobjects.com/js/external/paypal-button.min.js?merchant=DJOEURGOJ97S"'+
'data-button="buynow"'+
'data-name="socks"'+
'data-quantity="1"'+
'data-amount="{{dollarValue}}"'+
'data-currency="USD"'+
'data-shipping="0"'+
'data-tax="0"'+
'data-callback="https://gamerhoic.com/ipn/data.php"'+
'></script>';
要是这么简单就好了。
我尝试了很多建议,包括添加 ng-santize 和 $sce.trustAsHtml;
$sce.trustAsHtml('<script></script>');
我通读了Binding data in Angular js in string added via $sce.trustAsHtml彻底但它比我正在做的要复杂一些
使用 $sce.trustAtHtml 不渲染。如果我添加 {{paypal}} 我显然会显示 $scope.paypal '' 文本
<div bind-unsafe-html="paypal">{{paypal}}</div>
最佳答案
最好的方法是创建一个指令,然后在指令中你可以使用 angular.element
(基本上是 jQuery lite)将脚本添加到指令元素。以下应该很有效:
angular.module('myApp')
.directive('paypal', [function(){
return {
scope: {
dollarValue: '@'
},
link: function($scope, iElm, iAttrs, controller) {
var script = '<script async="async" src="' +
'https://www.paypalobjects.com/js/external/' +
'paypal-button.min.js?merchant=DJOEURGOJ97S"'+
'data-button="buynow"'+
'data-name="socks"'+
'data-quantity="1"'+
'data-amount="' + $scope.dollarValue + '"'+
'data-currency="USD"'+
'data-shipping="0"'+
'data-tax="0"'+
'data-callback="https://gamerhoic.com/ipn/data.php"'+
'></script>';
var scriptElem = angular.element(script)
iElm.append(scriptElem)
scriptElem.on('ready', ...)
}
};
}]);
注意这个指令有隔离作用域,它正在分配它的 dollarValue
范围属性到父级的字符串值(这样你就可以重复使用指令)
然后在您的 View html 中,使用新的自定义指令作为元素或属性,指定 dollarAmt
:
<paypal dollarAmt="{{dollarAmt}}"></paypal>
或
<div paypal dollarAmt="{{dollarAmt}}"></div>
你应该看到你的脚本标签被附加到它上面。您还可以替换指令中的包含元素(将 element
中的 link
重新分配给您想要的任何内容。)
看看这个 guide to creating custom directives , 真的很酷
更新
看起来创建这些脚本标签使用 document.createElement()
更简单而不是 angular.element
( see here )
我更改了上面的指令以使用此代码,并且能够在页面上看到 paypal 按钮:
var scriptElem = angular.element(document.createElement('script'))
scriptElem.attr("src", scriptUrl) // set var appropriately
element.append(scriptElem)
关于javascript - 在 angularjs 中渲染 <script> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554652/