Dynamically adding a url into a script tag in AngularJs

筅森魡賤 提交于 2019-12-11 09:55:25

问题


I'm implementing a payment gateway into my SPA built with angularjs.

The problem is that this payment gateway requires you to include a script with a id of the payment.

this is my current setup.... (note the controller just runs some server-side script, it returns all information about the payment I just need to get the id)

Here is my controller:

(function (){

var PaymentGateController = function ($scope, $rootScope, $state, paymentFactory, $sce) {

    $scope.ready = false;

    paymentFactory.getResult()
        .then(function (result) {
            $scope.ready = true;
            $scope.url = result.data.id;
        }, function(error) {
            console.log(error);
        });
}

PaymentGateController.$inject = ['$scope', '$rootScope','$state', 'paymentFactory', '$sce'];

angular.module('hcbcApp.paymentGate', []).controller('PaymentGateController', PaymentGateController);
}());

.. and here is my view:

<div ng-if="ready">
    <form action="https://peachpayments.docs.oppwa.com/tutorials/integration-guide#" class="paymentWidgets">VISA MASTER AMEX</form> 
    <script type="text/javascript" src="https://test.oppwa.com/v1/paymentWidgets.js?checkoutId={{url}}"></script>
</div>

回答1:


don't think you can do that, scripts are loaded first before the bootstrapping stage takes place in angular. Look for lazy loading solution. This post seems to fit what you want to do:

Single page application - load js file dynamically based on partial view




回答2:


This feels really dirty but it works so I'm going with it...

Added this to my controller:

    $scope.makeScript = function (url) {
        var script = document.createElement('script');
        script.setAttribute('src', url);
        script.setAttribute('type', 'text/javascript');
        document.getElementById('paymentDiv').appendChild(script);
    };

and then to this when I get the url

            $scope.url = "https://test.oppwa.com/v1/paymentWidgets.js?checkoutId=" + result.data.id;

            $scope.makeScript($scope.url);


来源:https://stackoverflow.com/questions/36311082/dynamically-adding-a-url-into-a-script-tag-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!