如何有条件地在 AngularJS 中应用 CSS 样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13813254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:00:31  来源:igfitidea点击:

How do I conditionally apply CSS styles in AngularJS?

cssangularjs

提问by Mark Rajcok

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. Suppose I want to allow each user to personalize how my site is presented. E.g., select from a fixed set of font sizes, allow user-definable foreground and background colors, etc.

Q2。假设我想允许每个用户个性化我的网站的呈现方式。例如,从一组固定的字体大小中进行选择,允许用户定义前景色和背景色等。

What's the best way to apply the CSS styling the user selects/inputs?

应用用户选择/输入的 CSS 样式的最佳方法是什么?

回答by Mark Rajcok

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-style- use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.
  • ng-showand ng-hide- use if you only need to show or hide something (modifies 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-switch- use instead of using several mutually exclusive ng-shows (modifies DOM)
  • ng-disabledand ng-readonly- use to restrict form element behavior
  • ng-animate- new in version 1.1.4, use to add CSS3 transitions/animations
  • ng-class- 当 CSS 样式集是静态的/提前已知时使用
  • ng-style- 当您无法定义 CSS 类时使用,因为样式值可能会动态更改。想想风格值的可编程控制。
  • ng-showng-hide- 如果您只需要显示或隐藏某些内容(修改 CSS),请使用
  • ng-if- 1.1.5 版中的新功能,如果您只需要检查单个条件(修改 DOM),请使用而不是更冗长的 ng-switch
  • ng-switch- 使用而不是使用几个相互排斥的 ng-shows(修改 DOM)
  • ng-disabledng-readonly- 用于限制表单元素行为
  • 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 (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.

正常的“Angular 方式”涉及将模型/范围属性绑定到将接受用户输入/操作的 UI 元素(即,使用 ng-model),然后将该模型属性关联到上述内置指令之一。

When the user changes the UI, Angular will automatically update the associated elements on the page.

当用户更改 UI 时,Angular 会自动更新页面上的关联元素。



Q1 听起来像是 ng-class 的一个好例子——CSS 样式可以在一个类中捕获。

ng-classaccepts 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
  1. 一串空格分隔的类名
  2. 类名数组
  3. 类名到布尔值的映射/对象

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-deleteclass:

假设使用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 听起来像是 ng-style 的一个好例子——CSS 样式是动态的,所以我们不能为此定义一个类。

ng-styleaccepts an "expression" that must evaluate to:

ng-style接受一个必须计算为:

  1. an map/object of CSS style names to CSS values
  1. 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为上述两个小提琴

The fiddle also contains an example of ng-showand 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.

小提琴还包含ng-showng-hide的示例。如果选中复选框,除了背景颜色变为粉红色外,还会显示一些文本。如果在文本框中输入“红色”,则 div 将隐藏。

回答by Timbergus

I have found problems when applying classes inside tableelements 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>). It seems that when you inspect the element with Developer Tools, the element.stylehas no style assigned. 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. This code works great for me:

当我已经将一个类应用于整个表格(例如,应用于奇数行的颜色)时,在表格元素中应用类时我发现了问题<myClass tbody tr:nth-child(even) td>。看来,当你检查与元素开发工具中,element.style没有分配的风格。因此ng-class,我没有尝试使用ng-style,而是尝试使用,在这种情况下,新的 CSS 属性确实出现在element.style. 这段代码对我很有用:

<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>

Myvaris what I am evaluating, and in each case I apply a style to each <td>depending on myvarvalue, that overwrites the current style applied by the CSS class for the whole table.

Myvar是我正在评估的内容,在每种情况下,我都会<td>根据myvar值对每个样式应用一种样式,这会覆盖 CSS 类为整个表格应用的当前样式。

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-classis the class to apply and a true or false statement. Trueapplies the class and falsedoesn't. So here we have two checks of the route of the page and an ORbetween them, so if we are in /route_aORwe are in route_b, the activeclass will be applied.

基本上,我们需要激活一个ng-class是要应用的类和一个 true 或 false 语句。True适用于该类,而false则不适用。所以这里我们对页面的路由和它们之间的OR进行了两次检查,所以如果我们在/route_aOR我们在 中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-styleis conditioned by three statements. 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 ORfor the whole response, the style remaining will be applied.

所以在第一个例子中,ng-style由三个语句决定。如果它们都为假,则不应用任何样式,但按照我们的逻辑,至少将应用一个,因此,逻辑表达式将检查哪个变量比较为真,因为非空数组始终为真,那将留下一个数组作为返回值,只有一个为真,考虑到我们对整个响应使用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 的图标

回答by Ashley Davis

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. It talks about this issue and numerous others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS

我发表了一篇关于使用 AngularJS+SVG 的文章。它讨论了这个问题和许多其他问题。http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS

回答by Nenad Jesic

span class="circle circle-{{selectcss(document.Extension)}}">

and code

和代码

$scope.selectcss = function (data) {
    if (data == '.pdf')
        return 'circle circle-pdf';
    else
        return 'circle circle-small';
};

css

css

.circle-pdf {
    width: 24px;
    height: 24px;
    font-size: 16px;
    font-weight: 700;
    padding-top: 3px;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    background-image: url(images/pdf_icon32.png);
}

回答by iamtankist

This solution did the trick for me

这个解决方案对我有用

<a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>

回答by michal-michalak

You can use ternary expression. There are two ways to do this:

您可以使用三元表达式。有两种方法可以做到这一点:

<div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>

or...

或者...

<div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>

回答by Dudi

Another option when you need a simple css style of one or two properties:

当您需要一个或两个属性的简单 css 样式时的另一种选择:

View:

看法:

<tr ng-repeat="element in collection">
    [...amazing code...] 
    <td ng-style="{'background-color': getTrColor(element.myvar)}">
        {{ element.myvar }}
    </td>
    [...more amazing code...]
</tr>

Controller:

控制器:

$scope.getTrColor = function (colorIndex) {
    switch(colorIndex){
        case 0: return 'red';
        case 1: return 'green';
        default: return 'yellow';
    }
};

回答by Ranga Reddy

See the following example

看下面的例子

<!DOCTYPE html>
    <html ng-app>
    <head>
    <title>Demo Changing CSS Classes Conditionally with Angular</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="res/js/controllers.js"></script>

    <style>

    .checkboxList {
        border:1px solid #000;
        background-color:#fff;
        color:#000;
        width:300px;
        height: 100px;
        overflow-y: scroll;
    }

    .uncheckedClass {
       background-color:#eeeeee;
       color:black;
    }
    .checkedClass {
        background-color:#3ab44a;
        color:white;
    }
    </style>

    </head>
    <body ng-controller="TeamListCtrl">
    <b>Teams</b>
    <div id="teamCheckboxList" class="checkboxList">

    <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

    <label>
    <input type="checkbox" ng-model="team.isChecked" />
    <span>{{team.name}}</span>
    </label>
    </div>
    </div>
    </body>
    </html>

回答by kumarharsh

As of AngularJS v1.2.0rc, ng-classand even ng-attr-classfail 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 ...
}

回答by sheelpriy

well i would suggest you to check condition in your controller with a function returning trueor false.

好吧,我建议您使用返回truefalse的函数检查控制器中的条件。

<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>

and in your controller check the condition

并在您的控制器中检查条件

$scope.getTodayForHighLight = function(today, date){
    return (today == date);
}