265

With AngularJS I'm using ng-class the following way:

<div class="bigIcon" data-ng-click="PickUp()" 
ng-class="{first:'classA', second:'classB', third:'classC', fourth:'classC'}[call.State]"/>

I'm wondering if I can use the if-else expression to do something similar to this:

<div class="bigIcon" data-ng-click="PickUp()" 
ng-class="{first:'classA', second:'classB', else:'classC'}[call.State]"/>

So whenever call.State differs from first or second use classC and avoid specifying each value?

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161

9 Answers9

533

Use nested inline if-then statements (Ternary Operators)

<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')">

for example :

<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">
    ...
</div>

And make sure it's readable by your colleagues :)

Community
  • 1
  • 1
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
110

you could try by using a function like that :

<div ng-class='whatClassIsIt(call.State)'>

Then put your logic in the function itself :

    $scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
     else
         return "ClassC";
    }

I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/

DotDotDot
  • 3,566
  • 2
  • 20
  • 22
  • 6
    This is a much better solution than nested ternary operators – David says Reinstate Monica Oct 23 '14 at 14:48
  • 2
    Love it. This keeps the html even cleaner than a simple ng-class conditional. – mrgnw Nov 13 '14 at 20:54
  • 18
    Problem with this approach is now you're making the controller aware of CSS classes. Not a good approach. Having a variable set in the controller and then determining which class to use in the HTML from the variable is the better solution. – VtoCorleone Nov 19 '14 at 19:34
  • 1
    This is just a hint on how you can do it, this problem was simple enough to be dealt with a ternary operator, but when you need more logic you don't want to do that in the HTML directly, one of the quickest solution is, like I did, to use a function in your controller for that (if you don't want the controller to be aware of the CSS, you can also watch and set a scope variable and use a condition in the HTML based on that value). But, if you have a bit more logic, or many repetitions, put this in a directive, it should be cleaner. The example was mostly about NOT putting logic in the HTML – DotDotDot Nov 20 '14 at 10:01
  • 1
    better than ternary operators if you need to add condition for more than 2 or 3 different class, separate the html with the logic :) – Raphaël VO Mar 17 '16 at 16:14
  • 1
    I agree to @VtoCorleone comment, Its not a good practice to decide the class from controller. It should be from HTML only. Controller can have some parameter to be set which decides the class to be used. – ismail baig Jul 24 '16 at 10:48
66

I had a situation where I needed two 'if' statements that could both go true and an 'else' or default if neither were true, not sure if this is an improvement on Jossef's answer but it seemed cleaner to me:

ng-class="{'class-one' : value.one , 'class-two' : value.two}" class="else-class"

Where value.one and value.two are true, they take precedent over the .else-class

joel.software
  • 1,505
  • 1
  • 12
  • 15
13

Clearly! We can make a function to return a CSS class name with following fully example. enter image description here

CSS

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

JS

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

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

Lewis Hai
  • 1,114
  • 10
  • 22
3

The above solutions didn't work for me for classes with background images somehow. What I did was I create a default class (the one you need in else) and set class='defaultClass' and then the ng-class="{class1:abc,class2:xyz}"

<span class="booking_warning" ng-class="{ process_success: booking.bookingStatus == 'BOOKING_COMPLETED' || booking.bookingStatus == 'BOOKING_PROCESSED', booking_info: booking.bookingStatus == 'INSTANT_BOOKING_REQUEST_RECEIVED' || booking.bookingStatus == 'BOOKING_PENDING'}"> <strong>{{booking.bookingStatus}}</strong> </span>

P.S: The classes that are in condition should override the default class i.e marked as !important

Kazim Homayee
  • 739
  • 6
  • 8
1

This is the best and reliable way to do this. Here is a simple example and after that you can develop your custom logic:

//In .ts
public showUploadButton:boolean = false;

if(some logic)
{
    //your logic
    showUploadButton = true;
}

//In template
<button [class]="showUploadButton ? 'btn btn-default': 'btn btn-info'">Upload</button>
Avtandil Kavrelishvili
  • 1,651
  • 3
  • 27
  • 37
0

A workaround of mine is to manipulate a model variable just for the ng-class toggling:

For example, I want to toggle class according to the state of my list:

1) Whenever my list is empty, I update my model:

$scope.extract = function(removeItemId) {
    $scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
    if (!$scope.list.length) {
        $scope.liststate = "empty";
    }
}

2) Whenever my list is not empty, I set another state

$scope.extract = function(item) {
    $scope.list.push(item);
    $scope.liststate = "notempty";
}

3) When my list is not ever touched, I want to give another class (this is where the page is initiated):

$scope.liststate = "init";

3) I use this additional model on my ng-class:

ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"
Bahadir Tasdemir
  • 10,325
  • 4
  • 49
  • 61
0

Use it this way:

    <div [ngClass]="{cssClass A: condition 1, cssClass B: condition 2, cssClass C: condition 3}">...</div>
BLACKRIGAN
  • 391
  • 4
  • 7
-3

You can try this method:

</p><br /><br />
<p>ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}<br /><br /><br />

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

You can get complete details from here.

ozahorulia
  • 9,798
  • 8
  • 48
  • 72
Ehtesham Shami
  • 125
  • 2
  • 7