Tommy
Tommy

Reputation: 177

Load external JavaScript file with document.write into AngularJS app

I got this external JavaScript file(Ad file), which has a document.write() in it. I have tried loading it with $http, and then injecting it into a document.createElement, but the Ad server doesn't support this method; $http.get.

I have tried ng-include in a script, but no work.

I need to load the script in the file, and the run the script. How do I do it?

<script ng-src=""></script> doesn't work either. It does not run the script.

Thanks.

Upvotes: 4

Views: 5052

Answers (3)

Tommy
Tommy

Reputation: 177

I ended up with this directive - helped made by my friend Dennis - that works in my situation. Hope it can help someone.

(function() {
    'use strict';

    angular
        .module('app')
        .directive('emediateScript', emediateScript);

    /* @ngInject */
    function emediateScript(Ad, $http) {
        var directive = {
            link: link,
            restrict: 'E',
            scope: {
                ad: '=ad',
            }
        };

        return directive;

        function link(scope, element, attrs){

            var _el = angular.element(element);

            var url = 'http://www.http.com';

            var request = {
                method: 'GET',
                url: url,
                headers: {
                    'X-Authentication': undefined
                }
            };

            if (url) {
                $http(request).then(function(response) {
                    var html = response.data.substr(16);
                    html = html.substring(0, html.length - 4);
                    _el.html(html);
                });
            }

        };
    };
})();

And HTML was;

<emediate-script></emediate-script>

Upvotes: 1

JLRishe
JLRishe

Reputation: 101652

If you're using jQuery (which it sounds like you are), there is a method for this:

$.getScript("http://my/script/url.js");

Upvotes: 1

Victor Marchuk
Victor Marchuk

Reputation: 13886

Why not simply create a <script> tag with jqLite?

$('body').append('<script type="application/javascript" src="http://localhost/test.js"></script>');

It seems to work perfectly with my test file.

Upvotes: 0

Related Questions