SnoWhite
SnoWhite

Reputation: 109

Inject JS file after controller processing

I'm struggling on something since quite a few days now. I got a view that get filled by my controller through an API call. No problem here, the HTML is rendered just fine.

$http.get(url).
    success(function(data, status, headers, config) {
        $scope.myHTML = html;
})

Element bound

<div ng-bind-html="myHTML"></div>

Now I got a JS file inside the page (included by bower) which need the content of the api call to run. But since it's include inside the page, it gets runned before the controller get executed as I've seen on the console.

Since I'm a beginner in AngularJS I may miss some basics, but I didnt found anything on how to include and run a JS file after the controller has been doing his work. I could get all the code inside the js file and paste it onto the controller but since it's a library witch CSS dependencies I would like to avoid that.

For short, how would you include and executed a JS library after an API call by the controller ?

Thanks in advance !

Upvotes: 1

Views: 286

Answers (1)

dfsq
dfsq

Reputation: 193291

Looks like this library you use is not very flexible and initialize itself on window.onload event without even providing a way to make it manually later. What you can do in this case is to sort of hook into window.onload event and load script dynamically.

For this it is convenient to create helper service which would load script on demand and do it only after necessary HTML is available in DOM.

It can look something like this:

app.controller('MainCtrl', function($scope, $sce, $http, windowLoadedHook) {

    $http.get(url).
    success(function(data) {
        // Set HTML first
        $scope.myHTML = $sce.trustAsHtml(data);

        // Load library and intercept its window.onload assignment so that
        // you invoke init function when AccesSlide tries to set event handler
        windowLoadedHook.load('path/to/library/AccesSlide.js');
    });

});

app.service('windowLoadedHook', function() {
    return {
        load: function(src) {
            // If document is already loaded then hook into assigment call
            if (document.readyState === 'complete') {
                Object.defineProperty(window, 'onload', {
                    set(handler) {
                        handler();
                    }
                });
            }

            // and load script file finally
            var script = document.createElement('script');
            script.src = src;
            document.body.appendChild(script);
        }
    };
});

Upvotes: 1

Related Questions