在angularjs中动态加载头部内容



我有两个css文件,我想有条件地使用其中的任何一个。如何动态加载css文件。我尝试了以下解决方案。

在控制器中,我有一个可变

$scope.style1 = "resources/css/style_responsive.css";

在index.html 中

<link id="base-style-responsive" ng-href={{style1}} rel="stylesheet">

但我似乎没有正确加载文件。有没有办法动态加载文件。我会非常感激的。请帮帮我。

尝试将$scope.style1更改为$rootScope.style1

这真的很难看,但因为这类事情很难做小提琴之类的。。。这可能是在不出现在您面前的情况下实现解决方案的最佳方式。

这是:

http://jsfiddle.net/Wa4Ea/

myApp.service('styleSheet', 
    function($compile, $rootScope) {
        var variableName = 'customStyleSheet';
        var element = angular.element("<link data-ng-href='{{" + variableName + "}}' rel='stylesheet' />");
        $compile(element)($rootScope);
        document.getElementsByTagName("head")[0].appendChild(element[0]);
        return {
            set: function (href) {
                $rootScope[variableName] = href;
            }
        };
    }
);

我不确定你到底在做什么,但你明白了。修改它以满足您的需求。

(无论如何,从被盗

Angular JS:动态加载CSS和JS文件

可以尝试更努力地搜索:p)

最新更新