Angular JS: Load CSS and JS files dynamically

前端 未结 5 1902
孤独总比滥情好
孤独总比滥情好 2020-12-15 08:20

I am in the middle of developing a web app. I am using AngularJS for loading all the files dynamically into the UI.

I have an index.html file into which

相关标签:
5条回答
  • 2020-12-15 08:25

    Currently I use angular-css: https://github.com/door3/angular-css Imho, it's one of the best and most flexible solutions at the moment.

    0 讨论(0)
  • 2020-12-15 08:40

    I used jquery to do the hardwork like this

    /** resolve will come inside your route .when() function **/
    resolve: {
            theme: function ($route, $q) {
                changeCss($route, $q);
            }
        }
    
    /** This will come just outside your route .when() function, make sure the following function shall be in scope of the route provider **/
        var changeCss = function ($route, $q) {
            var defer = $q.defer();
            // Change the CSS as per the param received
            if ($route.current.params.css != undefined) {
                if ($route.current.params.css === ‘dark’) {
                    loadCSS(“assets / css / dark.css”);
                    defer.resolve();
                }
                if ($route.current.params.css === ‘light’) {
                    loadCSS(“assets / css / light.css”);
                    defer.resolve();
                } else {
                    defer.resolve();
                }
            }
            return defer.promise;
        }
        var loadCSS = function (href) {
            var cssLink = $(“ < link rel = ’stylesheet’ type = ’text / css’ href = ’”+href + “‘ > ”);
            $(“head”).append(cssLink);
        };
    

    I have used Promise because this will make sure to load the css before it shows/load the angularjs route/page.

    0 讨论(0)
  • 2020-12-15 08:44
    app.controller('MyCtrl', function($scope,$compile) {
        $("#my").append( $compile("<script src='my.js'>")($scope) );
    });
    
    0 讨论(0)
  • 2020-12-15 08:48

    Just write a service to add CSS and JS files to the <head>

    Here is a example service which is used to dynamically load CSS files.You can modify it easily to load JS files.

    https://github.com/Yappli/angular-css-injector

    0 讨论(0)
  • 2020-12-15 08:51

    Instead of going by AngularJS way, i tried to load the files using JQuery. It worked for me. You can check this link for reference

    0 讨论(0)
提交回复
热议问题