使用angualrjs调用普通的javascript

时间:2016-03-30 15:27:55

标签: javascript angularjs cdata

我正在尝试将联盟跟踪的旧版javascript代码包含到angularjs应用

<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>

我需要调用上面的代码(用angualr vars填充占位符)然后调用它:

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

最好的方法是什么?我已经尝试将代码放入Angular函数中但没有成功我还尝试将变量传递到$ window并尝试将它们插入到CDATA中但没有成功。有什么想法吗?

我应该将此代码添加到包含在angualrjs控制器中的HTML页面中

1 个答案:

答案 0 :(得分:2)

你正在尝试的是不能直接使用angularjs。你需要做类似下面的事情

//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';
        //]]>
    }

}());

然后您需要通过传递所需数据从控制器调用此函数,如下所示

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

完成此操作后,您可以继续动态包含脚本,如下图所示

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

document.body.appendChild(scriptEl);