Search code examples
javascriptangularjscdata

call normal javascript using angualrjs


I'm trying to include legacy javascript code for affiliate tracking into an angularjs app

<script type="text/javascript">
        //<![CDATA[ 

        /*** Do not change ***/
        var AWIN = {};
        AWIN.Tracking = {};
        AWIN.Tracking.Sale = {};

        /*** Set your transaction parameters ***/
        AWIN.Tracking.Sale.amount = '{{order_total}}';
        AWIN.Tracking.Sale.orderRef = '{(order_id}}';
        AWIN.Tracking.Sale.parts = '{{cats}}';
        AWIN.Tracking.Sale.voucher = '';
        AWIN.Tracking.Sale.currency = 'GBP';
        AWIN.Tracking.Sale.test = '0';
        AWIN.Tracking.Sale.channel = 'aw';
        //]]>
    </script>

I need to call the above code (filling in the place holders with angualr vars) and then call this:

    <script src="https://www.dwin1.com/xxxx.js" type="text/javascript" defer="defer"></script>

What is the best way to do this? I've tried placing the code into an Angular function with no success I've also tried passing the vars down into $window and trying to insert them into the CDATA at my end with no success. Any ideas?


I should add this code sits in a HTML page wrapped in an angualrjs controller


Solution

  • what you are trying is not possible directly with angularjs. you need to do something like below

    //Note: this is a new JS file included in your main html
    
    (function() {
        "use strict";
    
        window.AWIN = {};
    
        window.populateAwin = function(args) {
            //<![CDATA[ 
    
            /*** Do not change ***/
            AWIN.Tracking = {};
            AWIN.Tracking.Sale = {};
    
            /*** Set your transaction parameters ***/
            AWIN.Tracking.Sale.amount = args.order_total;
            AWIN.Tracking.Sale.orderRef = args.order_id;
            AWIN.Tracking.Sale.parts = args.cats;
            AWIN.Tracking.Sale.voucher = '';
            AWIN.Tracking.Sale.currency = 'GBP';
            AWIN.Tracking.Sale.test = '0';
            AWIN.Tracking.Sale.channel = 'aw';
            //]]>
        }
    
    }());
    

    you then need to call this function from your controller by passing required data as shown below

    populateAwin({
       order_total: $scope.order_total,
       order_id: $scope.order_id,
       cats: $scope.cats
    });
    

    Once this is done, you can proceed with inclusion of script dynamically as shown below from your controller

    var scriptEl = document.createElement("script");
    scriptEl.type = "text/javascript";
    scriptEl.defer = "defer";
    scriptEl.src = "https://www.dwin1.com/xxxx.js";
    
    document.body.appendChild(scriptEl);