Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for organizing and loading CSS in Angular.js

Tags:

css

angularjs

In my Angular application I want to load the css files in a modular way - each module has it's own css file. This way I can add, remove or move modules easily.

The best way I found so far to do it is by creating 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 it's template css. Although I inject the path (by another service), still it feels like I'm breaking the seperation between the logic and the view.

It there any other elegant way (that doesn't includes packing the css files into one huge file)?

like image 749
Roy Tsabari Avatar asked Jun 02 '13 11:06

Roy Tsabari


1 Answers

If your target is HTML5 browser, and assuming that you have a view per module, you can use scoped stylesheets in your views to accomplish this. If you wish to use a css file, you can use @import syntax to load the css file into the <style> tag. Here is a HTML of a view:

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

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

Please note that many recommend against the use @import for performance reasons. In fact, you can see that there is slight delay between loading of the page and style being applied.

like image 170
marcoseu Avatar answered Oct 01 '22 23:10

marcoseu