1

i have 2 css files and i want to use any one of them conditionally. How can i load css files dynamically. I have tried the following solution.

In controller i have a variable

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

in index.html

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

But i doesn't seems to load the files properly. Is there any way work around to load files dynamically. I shall be so much thankful. Kindly help me.

||||||
0

Try this change $scope.style1 to $rootScope.style1.

||||||
  • Thanks for response : Got this "Error: $rootScope is not defined" – Shahzeb Khan Aug 30 '13 at 7:40
  • Ask for $rootScope in your controller's constructor. – Words Like Jared Aug 30 '13 at 7:45
  • @Shahzeb Are you sure it's okay to not put {{style1}} in double quotes? – Words Like Jared Aug 30 '13 at 7:52
  • @Words Like Jared : I removed the quotes but still not working. – Shahzeb Khan Aug 30 '13 at 7:55
  • Are you loading your styles above ng-view? – BKM Aug 30 '13 at 8:12
0

This is really ugly but since it's kind of hard to do fiddles and whatnot for this sort of thing... this may be the best way to implement a solution without being in front of you.

Here it is:

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;
            }
        };
    }
);

I'm not sure what you're doing, exactly, but you get the idea. Modify it to meet your needs.

(Anyway, stolen from:

Angular JS: Load CSS and JS files dynamically

You could try searching a little harder :P )

||||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.