AngularJS ng-class if-else expression

AngularjsNg Class

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

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

Solution 2 - Angularjs

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/

Solution 3 - Angularjs

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

Solution 4 - Angularjs

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

Solution 5 - Angularjs

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

Solution 6 - Angularjs

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>

Solution 7 - Angularjs

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

  4. I use this additional model on my ng-class:

    ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"

Solution 8 - Angularjs

Use it this way:

    <div [ngClass]="{cssClass A: condition 1, cssClass B: condition 2, cssClass C: condition 3}">...</div>

Solution 9 - Angularjs

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDor CohenView Question on Stackoverflow
Solution 1 - AngularjsJossef Harush KadouriView Answer on Stackoverflow
Solution 2 - AngularjsDotDotDotView Answer on Stackoverflow
Solution 3 - Angularjsjoel.softwareView Answer on Stackoverflow
Solution 4 - AngularjsLewis HaiView Answer on Stackoverflow
Solution 5 - AngularjsKazim HomayeeView Answer on Stackoverflow
Solution 6 - AngularjsAvtandil KavrelishviliView Answer on Stackoverflow
Solution 7 - AngularjsBahadir TasdemirView Answer on Stackoverflow
Solution 8 - AngularjsBLACKRIGANView Answer on Stackoverflow
Solution 9 - AngularjsEhtesham ShamiView Answer on Stackoverflow