Adding multiple class using ng-class

后端 未结 11 1366
不知归路
不知归路 2020-11-22 12:47

Can we have multiple expression to add multiple ng-class ?

for eg.

相关标签:
11条回答
  • 2020-11-22 13:19

    For the ternary operator notation:

    <div ng-class="expression1? 'class1 class2' : 'class3 class4'">
    
    0 讨论(0)
  • 2020-11-22 13:20

    Found another way thanks to Scotch.io

    <div ng-repeat="step in steps" class="step-container step" ng-class="[step.status, step.type]" ng-click="onClick(step.type)">
    

    This was my reference.PATH

    0 讨论(0)
  • 2020-11-22 13:23

    Below active and activemenu are classes and itemCount and ShowCart is expression/boolean values.

    ng-class="{'active' : itemCount, 'activemenu' : showCart}"
    
    0 讨论(0)
  • 2020-11-22 13:30

    An incredibly powerful alternative to other answers here:

    ng-class="[  { key: resulting-class-expression }[ key-matching-expression ], ..  ]"
    

    Some examples:

    1. Simply adds 'class1 class2 class3' to the div:

    <div ng-class="[{true: 'class1'}[true], {true: 'class2 class3'}[true]]"></div>
    

    2. Adds 'odd' or 'even' classes to div, depending on the $index:

    <div ng-class="[{0:'even', 1:'odd'}[ $index % 2]]"></div>
    

    3. Dynamically creates a class for each div based on $index

    <div ng-class="[{true:'index'+$index}[true]]"></div>
    

    If $index=5 this will result in:

    <div class="index5"></div>
    

    Here's a code sample you can run:

    var app = angular.module('app', []); 
    app.controller('MyCtrl', function($scope){
      $scope.items = 'abcdefg'.split('');
    }); 
    .odd  { background-color: #eee; }
    .even { background-color: #fff; }
    .index5 {background-color: #0095ff; color: white; font-weight: bold; }
    * { font-family: "Courier New", Courier, monospace; }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
    
    <div ng-app="app" ng-controller="MyCtrl">
      <div ng-repeat="item in items"
        ng-class="[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]]">
        index {{$index}} = "{{item}}" ng-class="{{[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]].join(' ')}}"
      </div>
    </div>

    0 讨论(0)
  • 2020-11-22 13:33

    To apply different classes when different expressions evaluate to true:

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

    To apply multiple classes when an expression holds true:

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

    or quite simply:

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

    Notice the single quotes surrounding css classes.

    0 讨论(0)
提交回复
热议问题