我们可以有多个表达式来添加多个ng-class吗?

如。

<div ng-class="{class1: expressionData1, class2: expressionData2}"></div>

如果是,谁能举个例子这样做。

.


当前回答

我用这个:

[ngClass]="[{
    'basic':'mat-basic-button', 
    'raised':'mat-raised-button', 
    'stroked':'mat-stroked-button'
}[ 
    button.style ?? 'raised'
]]"

其他回答

下面active和activemenu是类,itemCount和ShowCart是表达式/布尔值。

ng-class="{'active' : itemCount, 'activemenu' : showCart}"

对于三元运算符表示法:

<div ng-class="expression1? 'class1 class2' : 'class3 class4'">

我用这个:

[ngClass]="[{
    'basic':'mat-basic-button', 
    'raised':'mat-raised-button', 
    'stroked':'mat-stroked-button'
}[ 
    button.style ?? 'raised'
]]"

当不同表达式的值为true时应用不同的类:

<div ng-class="{class1 : expression1, class2 : expression2}">
    Hello World!
</div>

当一个表达式为真时应用多个类:

<!-- notice expression1 used twice -->
<div ng-class="{class1 : expression1, class2 : expression1}">
    Hello World!
</div>

或者很简单:

<div ng-class="{'class1 class2' : expression1}">
    Hello World!
</div>

注意css类周围的单引号。

另一种方法是创建一个函数来控制"使用多个类"

CSS

 <style>
    .Red {
        color: Red;
    }
    .Yellow {
        color: Yellow;
    }
      .Blue {
        color: Blue;
    }
      .Green {
        color: Green;
    }
    .Gray {
        color: Gray;
    }
    .b {
         font-weight: bold;
    }
</style>

脚本

<script>
    angular.module('myapp', [])
            .controller('ExampleController', ['$scope', function ($scope) {
                $scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
                $scope.getClass = function (strValue) {
                    if (strValue == ("It is Red"))
                        return "Red";
                    else if (strValue == ("It is Yellow"))
                        return "Yellow";
                    else if (strValue == ("It is Blue"))
                        return "Blue";
                    else if (strValue == ("It is Green"))
                        return "Green";
                    else if (strValue == ("It is Gray"))
                        return "Gray";
                }
        }]);
</script>

使用它

<body ng-app="myapp" ng-controller="ExampleController">

<h2>AngularJS ng-class if example</h2>
<ul >
    <li ng-repeat="icolor in MyColors" >
        <p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
    </li>
</ul>

你可以参考ng-class的完整代码页if example