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

Adding an onClick event to a React MUI Fab: A Step-by-Step Guide

I'm attempting to incorporate the Floating Action Button from MUI5. Visit: https://mui.com/material-ui/react-floating-action-button/ for more details. Upon adding an onClick event to the button, no action is triggered. Below is my code snippet: <G ...

Display and conceal various elements in Vue.js using a data list

I'm a beginner in Vue.js, currently using Vue+Webpack. I am trying to make each link display data based on their respective ids when clicked, and match with the show attribute. I have created this functionality in a .vue file. export default { el ...

Exploring the implementation of waterfall in a Node.js application

async.traverse(map, function(item, tnext){ async.waterfall([ function(wnext){ console.log("One"); //performing MongoDB queries db.collection.find().toArray(function(err){ if(err){ ...

Understanding how to utilize jQuery or prototype to interpret onclick event containing "setLocation(...)" can enhance the functionality

I am dealing with a specific tag: <button onclick="setLocation('http://mysite.com/checkout/cart/add/product/17/')" /> My goal is to trigger an ajax request when the button is clicked. I want to extract the URL segment "product/17" and app ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

I'm struggling with developing react applications due to problems with canvas elements

I am currently using an M1 MacBook Pro, with Node version 15.4.1 and npm version 7.0.15. When I ran the command npx create-react-app my-app, it gave me this output: I have attempted various solutions but keep encountering the same issue related to "canva ...

Issues Arising When Using $scope Variable as Datasource in Kendo UI Grid with AngularJS

I have tried multiple tips and tricks from various sources, but I still can't seem to solve my problem. My goal is to replace a trNgGrid with the Kendo UI Grid. The trNgGrid functions differently as it retrieves its data from a $scope variable named ...

Tips for utilizing Sass and CSS Modules within create-react-app

I've been using FileName.module.scss to style my react elements like this: // Component styling with SCSS import React from "react"; import Aux from '../../hoc/Aux'; import classes from './Layout.module.scss'; const lay ...

Can using the jQuery.clone method impact other functions?

Assuming $dom is a jQuery element, can the following line be safely removed if a is not utilized thereafter? var a = $dom.clone(true,true); When using $dom.clone(false,false), it appears that there are no side effects. I believe this method doesn't ...

Efficiently Extracting Information from JSON Objects

Currently, I am in the process of parsing a JSON file. Let's assume that the JSON data looks like this: {"data" : [ {"ID":12, country: "UK"}, {"ID":13, country: "USA"}, {"ID":14, country: "BRA"}, ]} Instead of just having three entries as show ...

Converting nested JSON to CSV for simplified data organization

I need help flattening JSON in order to parse it as a CSV. The current flattening process is not working correctly, as the customer.addresses field is being filled with 'addresstype: r' and then skipping all other fields such as city, countrycode ...

Exploring categories with AngularJS filtering

I dived into AngularJS today and embarked on creating a straightforward app featuring categories with items. The app showcases categories in a sidebar (aside.navigation) and displays all the items in the main view. My initial idea was to load all the item ...

Exploring Unicode in JavaScript to iterate through emojis with different skin tones

Currently, I am facing an issue where Javascript splits emojis with different skin colors into multiple characters instead of treating them as one. Emojis with a yellow skin color work fine and give me the desired results. For example: let emojis = [..." ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

Receive JSON data with camel-case in a Web API 2.0 using a model in pascal-case style

My attempt to execute a PUT call on my Web API involves configuring the WebApiConfig.cs file to send data back to my Web project in camel case format. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesCont ...

Unveiling the Mystery: Extracting the URL Parameter in AngularJS

Here is a link localhost/project/#/showprofile/18 I need to retrieve the parameter 18 in my view In the application file named app.js, I have the following configuration: .when('/showprofile/:UserID', { title: 'Show User Profile&apo ...

Interactive state for associated product within list without order

I am currently working on a project that involves an unordered list with separate list items. The menu design includes product images in the top list item and the corresponding product names in the list item below. I have successfully implemented a hover s ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

Once the template is fully loaded and rendered, I am looking for an event to trigger

Just dipping my toes into the world of AngularJS and feeling a bit lost. I'm on a mission to discover how to determine when a view has finished rendering its template. I've tried countless suggestions from all over the internet, but nothing seem ...