AngularJS ng-class if-else expression
Asked Answered
A

9

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?

Alcus answered 11/8, 2013 at 13:45 Comment(0)
C
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 :)

Cerell answered 23/2, 2014 at 16:13 Comment(7)
What if I need to add two classes?Pallaten
Sorry, i mean "a classe if this AND another class if that". Two class, two different conditions.Pallaten
@mircobabini, ng-class="{'class1': ##condition1## , 'class2': ##condition2## }" as you can see in the question aboveCerell
This is not something I want to see in the view. Way too much logic for the view.Alaniz
@Zehelvion I'd have to disagree. This is view logic. You wouldn't want to be dictating which column class to be using within your controller or a service.. this is where it should be.Quatre
@Routy Would you not rather apply a filter instead of cumbersome logic? Someone might need to reuse the code, what then? DuplicateAlaniz
Couldnt you/ why couldnt you just use ng-class="thisForm.$valid : "class1" : "class2".Erma
F
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/

Froissart answered 11/8, 2013 at 13:58 Comment(6)
This is a much better solution than nested ternary operatorsInexpert
Love it. This keeps the html even cleaner than a simple ng-class conditional.Stabler
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.Unvarnished
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 HTMLFroissart
better than ternary operators if you need to add condition for more than 2 or 3 different class, separate the html with the logic :)Fruitcake
I agree to @Unvarnished 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.Galleon
R
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

Rayford answered 23/5, 2014 at 15:44 Comment(0)
H
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

Hesterhesther answered 22/9, 2015 at 4:6 Comment(0)
C
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

Coonskin answered 10/2, 2017 at 13:53 Comment(0)
P
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>
Pelota answered 11/9, 2017 at 12:28 Comment(0)
C
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'}"
Conant answered 17/5, 2016 at 8:8 Comment(0)
L
0

Use it this way:

    <div [ngClass]="{cssClass A: condition 1, cssClass B: condition 2, cssClass C: condition 3}">...</div>
Larcener answered 10/1, 2020 at 3:17 Comment(0)
C
-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.

Cronk answered 2/2, 2018 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.