Template for organizing and loading CSS in Angular.js

In my Angular application, I want to upload css files in a modular way - each module has its own css file. That way I can easily add, remove or move modules.

The best way I've found so far is to create a service:

angular.module('cssLoadingService', []).factory("CssLoadingService", function () { return { loadCss: function (url) { if (document.createStyleSheet) { //IE document.createStyleSheet(url); } else { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = url; document.getElementsByTagName("head")[0].appendChild(link); } } }; }); 

Each controller loads a css template. Although I introduce the path (by another service), it still seems to me that I am breaking the separation between logic and representation.

Is there any other elegant way (which does not include packing css files into one huge file)?

+7
source share
1 answer

If your goal is an HTML5 browser, and if you have a view for each module, you can use sliding style sheets in your views to accomplish this. If you want to use the css file, you can use the @import syntax to load the css file into the <style> . Here is the HTML view:

 <div> <style scoped>@import url('main.css')</style> <h1>This is Main and should be Gray</h1> </div> 

Check this box . It worked for me in the latest version of Chrome (27.x) and Firefox (21.x) on Mac OS X.

Note that many recommend against using @import for performance reasons. In fact, you can see that there is a slight delay between the page loading and the applied style.

+2
source

All Articles