Html AngularJS ngClass 条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16529825/
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 08:21:28  来源:igfitidea点击:

AngularJS ngClass conditional

htmlcssangularjs

提问by ryanzec

Is there any way to make an expression for something like ng-classto be a conditional?

有什么办法可以表达像ng-class条件这样的东西吗?

For example, I have tried the following:

例如,我尝试了以下方法:

<span ng-class="{test: 'obj.value1 == \'someothervalue\''}">test</span>

The issue with this code is that no matter what obj.value1is, the class test is always applied to the element. Doing this:

这段代码的问题在于,无论是什么obj.value1,类测试总是应用于元素。这样做:

<span ng-class="{test: obj.value2}">test</span>

As long as obj.value2does not equal a truthy value, the class in not applied. Now I can work around the issue in the first example by doing this:

只要obj.value2不等于真值,就不会应用该类。现在我可以通过执行以下操作来解决第一个示例中的问题:

<span ng-class="{test: checkValue1()}">test</span>

Where the checkValue1function looks like this:

checkValue1函数如下:

$scope.checkValue1 = function() {
  return $scope.obj.value === 'somevalue';
}

I am just wondering if this is how ng-classis supposed to work. I am also building a custom directive where I would like to do something similar to this. However, I can't find a way to watch an expression (and maybe that is impossible and the reason why it works like this).

我只是想知道这ng-class是否应该起作用。我也在构建一个自定义指令,我想做类似的事情。但是,我找不到一种观看表达式的方法(也许这是不可能的,这也是它像这样工作的原因)。

Here is a plnkrto show what I mean.

这是一个plnkr来说明我的意思。

回答by Bertrand

Your first attempt was almost right, It should work without the quotes.

您的第一次尝试几乎是正确的,它应该可以在没有引号的情况下工作。

{test: obj.value1 == 'someothervalue'}

Here is a plnkr.

这是一个plnkr

The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here. If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.

ngClass 指令将适用于任何计算 truey 或 falsey 的表达式,有点类似于 Javascript 表达式,但有一些不同,你可以阅读这里。如果您的条件太复杂,那么您可以使用返回真值或假值的函数,就像您在第三次尝试中所做的那样。

Just to complement: You can also use logical operators to form logical expressions like

只是为了补充:您还可以使用逻辑运算符来形成逻辑表达式,例如

ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"

回答by Abhi

Using ng-class inside ng-repeat

在 ng-repeat 中使用 ng-class

<table>
    <tbody>
            <tr ng-repeat="task in todos"
                ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
              'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
                <td>{{$index + 1}}</td>
                <td>{{task.name}}</td>
                <td>{{task.date|date:'yyyy-MM-dd'}}</td>
                <td>{{task.status}}</td>
            </tr>
    </tbody>
</table>

For each status in task.status a different class is used for the row.

对于 task.status 中的每个状态,行使用不同的类。

回答by Kaushal Khamar

Angular JSprovide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.

Angular JSng-class Directive 中提供了这个功能。您可以在其中放置条件并分配条件类。您可以通过两种不同的方式实现这一点。

Type 1

类型 1

<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>

In this code class will be apply according to value of statusvalue

在这个代码类中将根据状态值的值应用

if statusvalue is 0then apply class one

如果状态值为0然后应用类一个

if statusvalue is 1then apply class two

如果状态值为1然后应用类2

if statusvalue is 2then apply class three

如果状态值为2,则应用第三



Type 2

类型 2

<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>

In which class will be apply by value of status

将按状态值应用于哪个类

if statusvalue is 1 or truethen it will add class test_yes

如果状态值为1 或 true那么它将添加类test_yes

if statusvalue is 0 or falsethen it will add class test_no

如果状态值为0 或 false那么它将添加类test_no

回答by AlikElzin-kilaka

I see great examples above but they all start with curly brackets (json map). Another option is to return a result based on computation. The result can also be a list of css class names (not just map). Example:

我在上面看到了很好的例子,但它们都以大括号(json 映射)开头。另一种选择是根据计算返回结果。结果也可以是一个 css 类名列表(不仅仅是地图)。例子:

ng-class="(status=='active') ? 'enabled' : 'disabled'"

or

或者

ng-class="(status=='active') ? ['enabled'] : ['disabled', 'alik']"

Explanation: If the status is active, the class enabledwill be used. Otherwise, the class disabledwill be used.

说明:如果状态为活动,enabled则将使用该类。否则,disabled将使用该类。

The list []is used for using multiple classes (not just one).

该列表[]用于使用多个类(不仅仅是一个)。

回答by Nimantha Harshana Perera

There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.

有一个简单的方法可以与 html 类属性和 if/else 速记一起使用。没有必要让它变得如此复杂。只需使用以下方法。

<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>

Happy Coding, Nimantha Perera

快乐编码,尼曼莎·佩雷拉

回答by aamir sajjad

Angular syntax is to use the :operator to perform the equivalent of an ifmodifier

Angular 语法是使用:运算符来执行if修饰符的等效操作

<div ng-class="{ 'clearfix' : (row % 2) == 0 }">

Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.

将 clearfix 类添加到偶数行。尽管如此,表达式可以是我们在正常条件下可以拥有的任何东西,它应该评估为真或假。

回答by Subhransu

I am going to show you two methods by which you can dynamically apply ng-class

我将向您展示两种可以动态应用 ng-class 的方法

Step-1

第1步

By using ternary operator

通过使用三元运算符

<div ng-class="condition?'class1':'class2'"></div>

Output

输出

If your condition is true then class1 will be applied to your element else class2 will be applied.

如果您的条件为真,则 class1 将应用于您的元素,否则将应用 class2。

Disadvantage

坏处

When you will try to change the conditional value at run time the class somehow will not changed. So I will suggest you to go for step2 if you have requirement like dynamic class change.

当您尝试在运行时更改条件值时,该类以某种方式不会更改。因此,如果您有动态类更改之类的要求,我会建议您执行第 2 步。

Step-2

第2步

<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>

Output

输出

if your condition matches with value1 then class1 will be applied to your element, if matches with value2 then class2 will be applied and so on. And dynamic class change will work fine with it.

如果您的条件与 value1 匹配,则 class1 将应用于您的元素,如果与 value2 匹配,则将应用 class2,依此类推。动态类更改可以很好地使用它。

Hope this will help you.

希望这会帮助你。

回答by Razan Paul

Using function with ng-class is a good option when someone has to run complex logic to decide the appropriate CSS class.

当有人必须运行复杂的逻辑来决定合适的 CSS 类时,将函数与 ng-class 一起使用是一个不错的选择。

http://jsfiddle.net/ms403Ly8/2/

http://jsfiddle.net/ms403Ly8/2/

HTML:

HTML:

<div ng-app>
  <div ng-controller="testCtrl">
        <div ng-class="getCSSClass()">Testing ng-class using function</div>       
    </div>
</div>

CSS:

CSS:

.testclass { Background: lightBlue}

JavaScript:

JavaScript:

function testCtrl($scope) {
    $scope.getCSSClass = function() {
     return "testclass ";
  }     
}

回答by Saeed

use this

用这个

<div ng-class="{states}[condition]"></div>

for example if the condition is [2 == 2], states are {true: '...', false: '...'}

例如,如果条件为 [2 == 2],则状态为 {true: '...', false: '...'}

<div ng-class="{true: 'ClassA', false: 'ClassB'}[condition]"></div>

回答by Ninad Kulkarni

For Angular 2, use this

对于 Angular 2,使用这个

<div [ngClass]="{'active': dashboardComponent.selected_menu == 'mapview'}">Content</div>