Incorporating a dynamic URL within a script tag with AngularJs

I am currently integrating a payment gateway into my Single Page Application (SPA) using AngularJS.

The issue I'm facing is that the payment gateway requires me to include a script with a specific ID for the payment process to work correctly.

This is how my setup looks at the moment: (Note that the controller executes some server-side script that fetches all information related to the payment, but I only need to extract the ID.)

Below is the code snippet for 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 this is how it appears in 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>

Answer №1

It may not be possible to achieve that directly, as scripts typically load before the bootstrapping phase in Angular. Consider implementing a lazy loading solution instead. Check out this post for guidance on dynamically loading JS files based on partial views:

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

Answer №2

Although it may seem a bit unconventional, this solution is effective so I'm embracing it...

Inserting the following code into my controller:

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

and then utilizing it when receiving the URL:

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

            $scope.createScript($scope.url);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ajax fails to provide a response

Hey there, I'm trying to save the response from an HTML page and store the content of that page. However, every time I try, I keep getting an error message. What am I doing incorrectly? <script type="text/jscript"> var page = ""; $.aj ...

Using jQuery to combine the values of text inputs and checkboxes into a single array or string

I need to combine three different types of items into a single comma-separated string or array, which I plan to use later in a URL. Is there a way to merge these three types of data together into one string or array? An existing POST string User input f ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

Learn how to retrieve a file in Express.js using an AJAX POST request

Can you guide me on how to download a file using Express.js? This is what I have attempted on the server side: router.post('/download',function(req,res){ var file = __dirname + '/'+req.body.path; console.log(file); res. ...

Comparing JSON files in JavaScript to identify and extract only the new objects

I need a way to identify and output the newly added objects from two JSON files based on their "Id" values. It's important for me to disregard changes in object positions within the files and also ignore specific key-value changes, like Greg's ag ...

Stop the replication of HTML/CSS styles during the extraction of content from a div

Is there a way to prevent the copying of CSS properties, such as font styles and sizes, when content is copied from a div? I want only the plain text to be copied to the clipboard, without any formatting applied. ...

Navigating with Angular 2: Expressing HTML 5 Routing Challenges

I'm currently working on a simple web application using Express 4 and Angular 2. The only Angular 2 specific aspect in this project is the utilization of its HTML5 router. Let me walk you through how the routing works in this app: There are two prim ...

Parent and router-outlet in Angular 4 fashion

Suppose we are presented with the following code: <div class="container"> <div class="row"> <div class="col-sm-4 col-md-3"> <app-sidebar></app-sidebar> </div> <div class="c ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Creating a modal dialog using a function in a TypeScript file

Hey there, fellow developers! I have a question that might seem simple. So, in my HTML code I've got a Modal Dialog that pops up using ng2 Bootstrap. It's working fine, but... I want to replace this line of code "<button class="btn btn-prim ...

Trouble with Angular.js HTTP POST communicating with MVC async Task<ActionResult> method

I'm having an issue trying to invoke an Async method in the MVC controller (like Login) from an Angular client, but the calls are failing. I've also attempted it using the Google Postman tool. // // POST: /Account/Login [HttpPost] ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Unable to retrieve the iframe variable from the parent as it returns undefined

I am trying to retrieve a variable within an iframe from the parent index.html. Here is the index.html code: <!doctype html> <html lang="en-us> <head> <title>Test</title> </head> <body> <p>Test& ...

Clicking elements reveal but page height remains unchanged?

Clicking on a label within #row-product_id_page-0-0 triggers the display of #row- elements as shown in the code snippet below: $('#row-product_id_page-0-0 label').click(function() { var str = $(this).find('.am-product-title').text ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Async function captures error being thrown

I am looking to implement an async function in place of returning a promise. However, I've run into an issue with rejecting using error throwing: async function asyncOperation() { throw new Error("Terminate this application."); } (async () => { ...

Leaflet OSM: Adjust map focus to the polygon's center

Looking to create an HTML file that integrates the Leaflet library to display an OpenStreetMap view with a centered polygon? I've been following a helpful discussion, but still unsure about how to center and autozoom an arbitrary polygon on the map. A ...

Having trouble showing Bootstrap Toasts on my website

I successfully implemented Toast functionality upon button click, but I am facing an issue where I have two buttons and I want a separate Toast to appear for each button click. How can I achieve this? Another problem I encountered is related to the docume ...