javascript - 如何在 js 代码中嵌入 Angular 指令样式?

标签 javascript angularjs

我有一个用 Angular 1.5 编写的项目,在升级到 Angular 2 之前,我希望达到这样的状态:

angular.module(..).directive('name', () => {
     return {
         restrict: 'A', 
         template: `
             <div> ... some template... </div>
         `,
         style: `// this is what I am missing
             div{
                // some css
             }
         `, 
         controller: function($scope){ ... }   
     }
})

我唯一缺少的是风格部分。我怎样才能得到它? Angular 1.x 支持吗?有没有一个工具可以帮助我获得此功能?

为了说清楚 - 我不是在询问作用域 css。
我不在乎这些规则是否是全局性的。
我只是希望能够在模板和 Controller 旁边编写CSS。

因此,如果您知道像 babel 这样的工具可以将样式部分提取到 css/scss 文件,那就符合条件。
它甚至可以是我可以用于此场景的通用解决方案。

最佳答案

取自 Reddit

To my knowledge, there is no way to do that "automatically". Personally when i create a component i just give a specific ID / class to the top element, and restrict the component's CSS to that element.

Example: my-component.html

<div class="my-component-wrapper">
 ....
 </div>

my-component.scss

.my-component-wrapper {
   // style that applies only to my component
}

不支持 Angular 1.5 组件上的 style 属性,或者它已在 docs 中提到过。

关于javascript - 如何在 js 代码中嵌入 Angular 指令样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40761496/

相关文章:

angularjs - 调试 $apply 已在进行中

javascript - 如何使用 AngularJS 处理数组?

javascript - Highstock basemap 未显示

javascript - 如何在 x 轴上绘制时间图 Highcharts.js

javascript - 我可以将 z-index 图层合并到单个图像中吗?

javascript - RxJS - 为什么我要使用 throwError 而不是简单地抛出错误?

javascript - 单击时使用 Angular JS 或 JS 显示隐藏链接

javascript - 在 Cookie 中存储用户偏好

javascript - 使用属性或特性创建 HTML 选择选项

javascript - AngularJS 应用程序中的网页抓取