What is the best way to conditionally apply a class?

后端 未结 22 2226
感动是毒
感动是毒 2020-11-22 09:12

Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex.

相关标签:
22条回答
  • 2020-11-22 09:30

    We can make a function to manage return class with condition

    <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) {
                        switch(strValue) {
                            case "It is Red":return "Red";break;
                            case "It is Yellow":return "Yellow";break;
                            case "It is Blue":return "Blue";break;
                            case "It is Green":return "Green";break;
                            case "It is Gray":return "Gray";break;
                        }
                    }
            }]);
    </script>
    

    And then

    <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>
    <hr/>
    <p>Other way using : ng-class="{'class1' : expression1, 'class2' : expression2,'class3':expression2,...}"</p>
    <ul>
        <li ng-repeat="icolor in MyColors">
            <p ng-class="{'Red':icolor=='It is Red','Yellow':icolor=='It is Yellow','Blue':icolor=='It is Blue','Green':icolor=='It is Green','Gray':icolor=='It is Gray'}" class="b">{{icolor}}</p>
        </li>
    </ul>
    

    You can refer to full code page at ng-class if example

    0 讨论(0)
  • 2020-11-22 09:31

    If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:

    ng:class="{true:'selected', false:''}[$index==selectedIndex]"
    

    Please note the old syntax with colon.

    There is also a new better way of applying classes conditionally, like:

    ng-class="{selected: $index==selectedIndex}"
    

    Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.

    However these ways are not functionally equal. Here is an example:

    ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
    

    We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.

    0 讨论(0)
  • 2020-11-22 09:31

    ng-class supports an expression that must evaluate to either

    1. A string of space-delimited class names, or
    2. An array of class names, or
    3. A map/object of class names to boolean values.

    So, using form 3) we can simply write

    ng-class="{'selected': $index==selectedIndex}"
    

    See also How do I conditionally apply CSS styles in AngularJS? for a broader answer.


    Update: Angular 1.1.5 has added support for a ternary operator, so if that construct is more familiar to you:

    ng-class="($index==selectedIndex) ? 'selected' : ''"
    
    0 讨论(0)
  • 2020-11-22 09:31

    partial

      <div class="col-md-4 text-right">
          <a ng-class="campaign_range === 'thismonth' ? 'btn btn-blue' :  'btn btn-link'" href="#" ng-click='change_range("thismonth")'>This Month</a>
          <a ng-class="campaign_range === 'all' ? 'btn btn-blue' :  'btn btn-link'" href="#" ng-click='change_range("all")'>All Time</a>
      </div>
    

    controller

      $scope.campaign_range = "all";
      $scope.change_range = function(range) { 
            if (range === "all")
            {
                $scope.campaign_range = "all"
            }
            else
            {  
                $scope.campaign_range = "thismonth"
            }
      };
    
    0 讨论(0)
  • 2020-11-22 09:31

    If you are using angular pre v1.1.5 (i.e. no ternary operator) and you still want an equivalent way to set a value in both conditions you can do something like this:

    ng-class="{'class1':item.isReadOnly == false, 'class2':item.isReadOnly == true}"
    
    0 讨论(0)
  • 2020-11-22 09:34

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

    <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);
    }
    
    0 讨论(0)
提交回复
热议问题