Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get script location from server before angular is loaded

I need dynamically add script in my index.html page depending on the application version. I have a controller that returns app version and tried to do this using angularjs:

    var resourceLoader = angular.module('MyTabs', []);
    resourceLoader.controller('ResourceLoaderController', ['$scope', '$http', function ($scope, $http) {
        $scope.getVersion = function() {
            $http.get('/version/get').then(function (response) {
                $scope.version = response.data;
                var link = document.createElement("link");
                link.setAttribute("type", "text/css");
                link.setAttribute("rel", "stylesheet");
                link.setAttribute("href", '/r/' + $scope.version +'/css/app.css');
                document.getElementsByTagName("head")[0].appendChild(link);

                var script = document.createElement("script");
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", '/r/' + $scope.version +'/js/app.js');
                document.getElementsByTagName("head")[0].appendChild(script);
            });
        };

        $scope.getVersion();
    }]);

It works but there are angular controllers in app.js, and I get an error in runtime that AuthController, used in index.html, is undefined.

Is there any way to get application version from server and include script before angularjs starts processes the web page?

like image 220
Kirill Avatar asked Dec 23 '15 14:12

Kirill


1 Answers

How AngularJS works is it creates the app and builds all controller/directives/services dictionaries when you include the .js files.

By adding another script after AngularJS has finished building those, the controllers won't get added to the app.

You need to look up how to add controllers dynamically: Loading an AngularJS controller dynamically

Your other choice is getting the version and script BEFORE your html references and builds the AngularJS dependency. This way by the time AngularJS starts doing its magic, the scripts already will be loaded.

like image 96
AlexD Avatar answered Oct 12 '22 10:10

AlexD