Load and unload external stylesheets dynamically in AngularJS application

2.6k Views Asked by At

I have two routes/views in my AngularJS application that are using conflicting CSS. I have two separate external stylesheets that I want to use for these routes. For example foo.css for foo route and bar.css for bar route. That way I can resolve the conflict.

However, I will have to load bar.css and unload foo.css when navigating from foo to bar.

How do I do this? Is there a library/module that can help me to achieve this scenario?

I've looked into ocLazyLoad, but I'm not sure how to unload the loaded CSS.

1

There are 1 best solutions below

5
On

AngularJS Way

In a comment below, the OP suggested the way that seems most appropriate to me in AngularJS - using the ng-disabled directive. You just have to make <html> your ng-app attribute element so that the directive gets properly executed.

<link rel="stylesheet" href="/path/to/style-1.css" ng-disabled="theme.name === 'theme1'">
<link rel="stylesheet" href="/path/to/style-2.css" ng-disabled="theme.name === 'theme2'">

This way both styles get loaded immediately (causing no flicker on change later). Different approach would be needed if some of the styles should not be loaded initially.

Original Answer

See this question. Then just find the appropriate <link> tags and enable/disable them at will. I don't think this has anything to do with AngularJS.