本文翻译自:How do I conditionally apply CSS styles in AngularJS?

Q1. Q1。 Suppose I want to alter the look of each "item" that a user marks for deletion before the main "delete" button is pressed. 假设我想要在按下主“删除”按钮之前改变用户标记为删除的每个“项目”的外观。 (This immediate visual feedback should eliminate the need for the proverbial "are you sure?" dialog box.) The user will check checkboxes to indicate which items should be deleted. (这种直接的视觉反馈应该消除了对“你确定吗?”对话框的谚语的需要。)用户将检查复选框以指示应删除哪些项目。 If a checkbox is unchecked, that item should revert back to its normal look. 如果未选中复选框,则该项应恢复为正常状态。

What's the best way to apply or remove the CSS styling? 应用或删除CSS样式的最佳方法是什么?

Q2. Q2。 Suppose I want to allow each user to personalize how my site is presented. 假设我想允许每个用户个性化我的网站的呈现方式。 Eg, select from a fixed set of font sizes, allow user-definable foreground and background colors, etc. 例如,从一组固定的字体大小中选择,允许用户可定义的前景色和背景色等。

What's the best way to apply the CSS styling the user selects/inputs? 应用用户选择/输入的CSS样式的最佳方法是什么?


#1楼

参考:https://stackoom.com/question/vxSQ/如何在AngularJS中有条件地应用CSS样式


#2楼

Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically: Angular提供了许多内置指令,用于有条件地/动态地操纵CSS样式:

  • ng-class - use when the set of CSS styles is static/known ahead of time ng-class - 当CSS样式集是静态/提前知道时使用
  • ng-style - use when you can't define a CSS class because the style values may change dynamically. ng-style - 在无法定义CSS类时使用,因为样式值可能会动态更改。 Think programmable control of the style values. 想想风格值的可编程控制。
  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS) ng-showng-hide - 如果你只需要显示或隐藏某些东西就可以使用(修改CSS)
  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM) ng-if - 1.1.2版中的新增功能,如果您只需要检查单个条件(修改DOM),请使用代替更详细的ng-switch
  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM) ng-switch - 使用而不是使用几个互斥的ng-shows(修改DOM)
  • ng-disabled and ng-readonly - use to restrict form element behavior ng-disabledng-readonly - 用于限制表单元素行为
  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations ng-animate - 1.1.4版中的新增功能,用于添加CSS3过渡/动画

The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (ie, use ng-model), and then associating that model property to one of the built-in directives mentioned above. 正常的“Angular方式”涉及将模型/范围属性绑定到将接受用户输入/操作(即,使用ng-model)的UI元素,然后将该模型属性与上述内置指令之一相关联。

When the user changes the UI, Angular will automatically update the associated elements on the page. 当用户更改UI时,Angular将自动更新页面上的关联元素。


Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class. Q1听起来像ng-class的好例子 - CSS样式可以在类中捕获。

ng-class accepts an "expression" that must evaluate to one of the following: ng-class接受必须评估为以下之一的“表达式”:

  1. a string of space-delimited class names 一串以空格分隔的类名
  2. an array of class names 一组类名
  3. a map/object of class names to boolean values 类名的映射/对象为布尔值

Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class: 假设您的项目使用某些数组模型的ng-repeat显示,并且当选中项目的复选框时,您想要应用pending-delete类:

 <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}"> ... HTML to display the item ... <input type="checkbox" ng-model="item.checked"> </div> 

Above, we used ng-class expression type #3 - a map/object of class names to boolean values. 上面,我们使用ng-class表达式#3 - 类名的映射/对象到布尔值。


Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this. Q2听起来像ng风格的好例子 - CSS样式是动态的,所以我们不能为此定义一个类。

ng-style accepts an "expression" that must evaluate to: ng-style接受必须评估为的“表达式”:

  1. an map/object of CSS style names to CSS values CSS样式名称的地图/对象到CSS值

For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer): 对于一个人为的例子,假设用户可以在texbox中输入颜色名称作为背景颜色(jQuery颜色选择器会更好):

 <div class="main-body" ng-style="{color: myColor}"> ... <input type="text" ng-model="myColor" placeholder="enter a color name"> 

Fiddle for both of the above. 小提琴兼得以上。

The fiddle also contains an example of ng-show and ng-hide . 小提琴还包含ng-show和ng-hide的示例。 If a checkbox is checked, in addition to the background-color turning pink, some text is shown. 如果选中复选框,则除了背景颜色变为粉红色外,还会显示一些文本。 If 'red' is entered in the textbox, a div becomes hidden. 如果在文本框中输入“红色”,则会隐藏div。


#3楼

This works well when ng-class can't be used (for example when styling SVG): 当不能使用ng-class时(例如在设置SVG样式时),这很有效:

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4) (我认为你需要使用最新的不稳定Angular来使用ng-attr-,我目前正在使用1.1.4)

I have published an article on working with AngularJS+SVG. 我发表了一篇关于使用AngularJS + SVG的文章。 It talks about this issue and numerous others. 它谈论这个问题和许多其他问题。 http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS


#4楼

As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute) 从AngularJS v1.2.0rc开始, ng-class甚至ng-attr-class失败了SVG元素(它们确实更早,即使在class属性中有正常绑定)

Specifically, none of these work now: 具体来说,现在这些都不起作用:

ng-class="current==this_element?'active':' ' "
ng-attr-class="{{current==this_element?'active':' '}}"
class="class1 class2 .... {{current==this_element?'active':''}}"

As a workaround, I've to use 作为一种解决方法,我要使用

ng-attr-otherAttr="{{current==this_element?'active':''}}"

and then style using 然后使用样式

[otherAttr='active'] {... styles ...
}

#5楼

I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td> ). 当我已经将一个类应用于整个表时,我在表元素中应用类时遇到了问题(例如,应用于奇数行的颜色<myClass tbody tr:nth-child(even) td> )。 It seems that when you inspect the element with Developer Tools , the element.style has no style assigned. 看来,当您使用Developer Tools检查元素时, element.style没有分配样式。 So instead of using ng-class , I have tried using ng-style , and in this case, the new CSS attribute does appear inside element.style . 因此,我尝试使用ng-style而不是使用ng-class ,在这种情况下,新的CSS属性确实出现在element.style This code works great for me: 这段代码对我很有用:

<tr ng-repeat="element in collection">[...amazing code...]<td ng-style="myvar === 0 && {'background-color': 'red'} ||myvar === 1 && {'background-color': 'green'} ||myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>[...more amazing code...]</tr>

Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table. Myvar是我正在评估的,并且在每种情况下我都根据myvar值对每个<td>应用一个样式,它会覆盖整个表的CSS类所应用的当前样式。

UPDATE UPDATE

If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure: 例如,如果要将表应用于表,则在访问页面时或在其他情况下,可以使用此结构:

<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">

Basically, what we need to activate a ng-class is the class to apply and a true or false statement. 基本上,我们需要激活ng-class的是要应用的类以及true或false语句。 True applies the class and false doesn't. True适用于类而false不适用。 So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b , the active class will be applied. 所以这里我们有两个页面路由检查和它们之间的OR ,所以如果我们在/route_a 或者我们在route_b ,那么将应用活动类。

This works just having a logic function on the right that returns true or false. 这只是在右边有一个返回true或false的逻辑函数。

So in the first example, ng-style is conditioned by three statements. 所以在第一个例子中, ng-style由三个语句决定。 If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied. 如果所有这些都是假的,则不应用任何样式,但是遵循我们的逻辑,将至少应用一个,因此,逻辑表达式将检查哪个变量比较为真,并且因为非空数组始终为真,所以将数组作为返回并且只有一个为true,考虑到我们使用OR作为整个响应,将应用剩余的样式。

By the way, I forgot to give you the function isActive(): 顺便说一句,我忘了给你功能isActive():

$rootScope.isActive = function(viewLocation) {return viewLocation === $location.path();
};

NEW UPDATE 新的更新

Here you have something I find really useful. 在这里你有一些我觉得非常有用的东西。 When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div , you can use the following code (very useful in ng-repeat ): 当您需要根据变量的值应用类时,例如,取决于div内容的图标,您可以使用以下代码(在ng-repeat非常有用):

<i class="fa" ng-class="{ 'fa-github'   : type === 0,'fa-linkedin' : type === 1,'fa-skype'    : type === 2,'fa-google'   : type === 3 }"></i>

Icons from Font Awesome 来自Font Awesome的图标


#6楼

One thing to watch is - if the CSS style has dashes - you must remove them. 需要注意的一件事是 - 如果CSS样式有破折号 - 你必须删除它们。 So if you want to set background-color , the correct way is: 所以如果你想设置background-color ,正确的方法是:

ng-style="{backgroundColor:myColor}"

如何在AngularJS中有条件地应用CSS样式?相关推荐

  1. 在vue中引入css,详解在Vue中有条件地使用CSS类

    详解在Vue中有条件地使用CSS类 2019-01-07 编程之家 https://www.jb51.cc 编程之家收集整理的这篇文章主要介绍了详解在Vue中有条件地使用CSS类,编程之家小编觉得挺不 ...

  2. 山东标梵讲解如何在HTML文档中使用CSS样式表?

    在HTML中,我们可以通过以下三种不同的方法将CSS样式表链接到Html文档: 使用内联样式 使用嵌入样式或内部样式 使用外部样式 使用内联样式 这是将CSS样式添加到HTML文档或代码中的最简单方法 ...

  3. 如何在AngularJS的ng-options中设置value属性?

    本文翻译自:How do I set the value property in AngularJS' ng-options? Here is what seems to be bothering a ...

  4. 如何在AngularJS中使用ng-repeat迭代键和值?

    本文翻译自:How to iterate over the keys and values with ng-repeat in AngularJS? In my controller, I have ...

  5. [css] 一个项目中有很多无用的css代码,怎么找到并清除这些无用的代码?

    [css] 一个项目中有很多无用的css代码,怎么找到并清除这些无用的代码? 1.使用浏览器插件 2.使用PurifyCSS 3.chrome浏览器 F12审查元素的Audits,手动删 个人简介 我 ...

  6. 如何使用ES6在JavaScript中有条件地构建对象

    by Knut Melvær 通过纳特·梅尔瓦 如何使用ES6在JavaScript中有条件地构建对象 (How to conditionally build an object in JavaScr ...

  7. 数据绑定如何在AngularJS中运行?

    本文翻译自:How does data binding work in AngularJS? How does data binding work in the AngularJS framework ...

  8. 如何在React JS组件和React JS App中添加CSS样式?

    In this tutorial, we will only work with CSS styles. Please ensure you have basic knowledge of HTML, ...

  9. 如何在html添加css样式表,网页中添加CSS样式表的四种方式

    本文向大家描述一下网页中添加CSS样式表的四种方式,首先让我们来看一下CSS样式表文件的优势,主要体现在两个方面,请看下文详细介绍. CSS样式表文件的优势表现在两个方面: ***,简化了网页的格式代 ...

最新文章

  1. mac使用的快捷方式
  2. php 不刷新提交,提交表单而不刷新页面ajax,php,javascript?
  3. ASP.NET企业开发框架IsLine FrameWork系列之二--命名空间与契约
  4. “球鞋一面墙,堪比一套房” 央视评炒鞋乱象:呼吁“鞋穿不炒”
  5. diamond专题(一)– 简介和快速使用
  6. 【渝粤教育】国家开放大学2018年春季 0688-22T老年精神障碍护理 参考试题
  7. 注册表如何管理右键菜单
  8. Fastjson源码阅读:缺陷静态检查(上)
  9. 【每日爬虫】:生产者与消费者模式爬取王者荣耀壁纸
  10. 发布博客支持关闭图片水印啦【CSDN产品周报第10期】
  11. android服务实现播放器,Android实现简单音乐播放器(MediaPlayer)
  12. 从零开始安装和配置vim (还是vscode香)
  13. 初识小熊派——小熊派硬件分析
  14. 正则表达式(RegExp)
  15. 《用计算机写日记》》教学课件,写日记教学课件 [观察日记教学课件]
  16. 云厂商下一块必争之地就是它了!
  17. SVN客户端安装和服务器搭建
  18. 怎么跟学计算机的聊天,win7通过局域网进行电脑之间聊天的方法-电脑自学网
  19. 《利用python进行数据分析》——第6章 数据加载、存储与文件格式——读书笔记
  20. (转载)解密 [Dekrypt24@tutanota.com].mkp 病毒

热门文章

  1. 汇编指令-adr与ldr伪汇编区别(8)
  2. 基于ping++第三方集成各类支付
  3. Linux/Unix系统下nginx+php安装简明教程
  4. windows 2003 复制大文件提示系统资源不足的官方处理方法
  5. Silverlight/Windows8/WPF/WP7/HTML5周学习导读(8月13日-8月19日)
  6. 网络工程师职业规划(三)
  7. RedisTemplate和StringRedisTemplate的区别
  8. 当桌面的快捷方式图标左下角出现一个X(叉)的时候应该怎么去掉
  9. servlet路径跳转
  10. nodejs模块之event