angularjs 指令:如何封装 css? [英] angularjs directive : how to encapsulate css?

查看:28
本文介绍了angularjs 指令:如何封装 css?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在完成 Web Components 项目后,我将回到 AngularJS.我很沮丧,因为我找不到让指令保持其 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).

使用 web 组件我没有这个问题,因为已经有一个样式标签可以嵌入到模板中.

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

AngularJS 指令不是这种情况.

That's not the case with AngularJS directives.

直到这里我看到的是:

1) 在外部文件中定义 CSS 规则:my-directive {color:red;},但这不是封装.

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

2) 用 element.css({}) 定义一个内部规则;内部链接函数,但在这种情况下,样式是内联应用的,因此太重,不能被外部 css 轻易覆盖.

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.

还有其他方法吗?

谢谢

推荐答案

GitHub 上已经创建了一个 angular 服务,您可以动态加载您的 css 文件,也许它会有所帮助

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

或者你可以给 GruntJS 一个机会,你可以有一个非常好的项目结构,每个模块/文件夹都可以有自己的 css 文件,Grunt 会将所有这些文件打包成一个(或多个,这取决于你如何配置).它易于管理和更改,而且您的页面上只加载了一个文件.也许这些链接可以帮助您找到可以帮助您的 Grunt 模块.

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

这篇关于angularjs 指令:如何封装 css?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆