Search code examples
angularjsangularjs-directiveweb-component

angularjs directive : how to encapsulate css?


After a project with Web Components, i'm going back to AngularJS. I'm frustrated by the fact I can't find a proper way for a directive to keep its CSS internal (or encapsulated).

With web component I hadn't this problem since there is already a style tag that can be embedded in the template.

That's not the case with AngularJS directives.

Until here what I saw is :

1) define an CSS rule in an external file : my-directive {color:red;}, but this is not encapsulation.

2) define an internal rule with element.css({}); inside link function, but in this case the style is applied inline and thus is too heavy and cannot be easily override by external css.

Are there other ways ?

Thanks


Solution

  • There is a one angular service already created on GitHub, you can load your css files dinamically, maybe it can be helpful

    https://github.com/Yappli/angular-css-injector

    Or you can give a chance to GruntJS and you can have a very nice project structure, every module/folder can have own css file, and Grunt will bundle all that files into one (or many, it depends how you configure). It's easy to manage and change, but also you have only one file loaded on your page. Maybe these links can be helpful to find Grunt module that can help you.

    https://www.npmjs.org/package/grunt-contrib-cssmin