Search code examples
javascripthtmlcssangularjsng-class

How to do an if-else using ngClass?


I am using AngularJS on my site, and have a widget displayed on one of my webpages, and want to change the style element of some text displayed in a div tag depending on whether a boolean value associated with that text is true or false.

An alarm is raised on the web page, and displayed in the widget when an integer variable reaches a certain limit (i.e. when x >= 100, the alarmRaised boolean is set to true). The value of the variable is always displayed on the page, and is being updated every 30 seconds.

When the alarm is raised, a warning is raised (and displayed on a separate page)- the user has the option to accept that warning. When the warning has been accepted, I want the text showing the value of the variable to be displayed in one colour, and when it hasn't, I want to display it in another colour.

The HTML where this 'alarm' text is displayed is inside one of the JS functions for that page:

.directive('tagBox', function($timeout, tag, colourFilter){
    return{
        restrict: 'E',
        scope: {
            ...
        },
        template: ...
            ...
            '<div data-ng-repeat="alarm in alarms" data-ng-class="{\'text-warning\':alarm.accepted.value, \'text-danger\':!alarm.accepted.value}">{{alarm.message.value}}</div>'

Inside the above <div></div> tag, I want to use some in-line JS to say: "if the value of alarm.accepted.value is true, display the value of alarm.message.value in one colour; if it's false, display it in another colour... How would I do this?


Solution

  • As you are using ngClass in your template, you may want to use the ternary operator in ngClass:

    <div ng-class="alarm.accepted.value ? 'text-warning' : 'text-danger'">
        ...
    </div>
    

    Note that it works since Angular 1.1.4. If you are using Angular 1.1.1, ternary operator is not supported. You can use instead:

    <div ng-class="{'text-warning': alarm.accepted.value, 'text-danger': !alarm.accepted.value}">
        ...
    </div>
    

    Or:

    <div ng-class="{true:'text-warning', false:'text-danger'}[alarm.accepted.value]">
        ...
    </div>