如何使用CSS样式的AngularJS指令? [英] How to CSS style AngularJS directive?

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

问题描述

假设我有一个带有模板的指令"mydirect",该模板包含许多带有许多嵌套类的div.例如:

Assuming I have a directive "mydirect" with a template that contains a lot of divs with a lot of nested classes. For example:

<div class="mydirect">
  <div class="classA">
    <div class="subclassA">
      <div class="subclassB">
      </div>
    <div class="classB"></div>
</div>

我注意到,尽管使用css文件中的类名("mydirectstyle.css"),并使用我的指令将其包含在index.html中:

I noticed that despite having the classnames in a css file ("mydirectstyle.css") and it being included in index.html, using my directive:

angular.module("MyApp", []).
  directive('mydirect', function() {
    return {
      restrict: 'E',
      replace: true,
      template: '-All that Html here-'
    };
  });

任何CSS属性都不会应用于该属性.将我的所有样式应用于多个类的最佳方法是什么?可以这样做,而不必手动选择每个元素并设置单独的CSS属性吗?

None of the CSS properties are applied to it whatsoever. What is the best way to apply all my styles to those multiple classes? Can it be done such that I don't have to manually select each element and set individual CSS properties?

我的index.html页面包含一个<mydirect> </mydirect>,它已由上面显示的指令模板替换.

My index.html page contains a <mydirect> </mydirect> that gets replaced by the directive template shown above.

推荐答案

使用实际的元素名称在DOM中创建指令要容易得多,而不是尝试使用class方法.出于两个原因:1)具有<mydirect><div class="mydirect">更具可读性,并且2)您只需使用适当的css语法即可获得相同的样式易用性.

Its much easier to use actual element names to create directives in your DOM rather than trying to use the class method. For two reasons: 1) its much more readable to have <mydirect> vs <div class="mydirect"> and 2) you can get the same ease of styling by just using the proper css syntax.

按原样保留您的指令,除了将其更改为restrict: 'EA'(该文档的此处)和replace: false,如下所示:

Leave your directive just the way it is, except change it to restrict: 'EA' (docs for that here) and replace: false, as shown here:

.directive('mydirect', function() {
    return {
        restrict: 'EA',
        replace: false,
        template: '-All that Html here-'
    };
});

以下是您现在可以使用的选项以及如何配置相应的CSS以获取所需的样式,如

Here are the options you can now use and how to configure the corresponding CSS to get the styles you want, as shown in this jsbin:

希望有帮助.

这篇关于如何使用CSS样式的AngularJS指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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