Search code examples
angularjsangularjs-scopeng-classng-showangular-ng-if

AngularJS - Using Multiple Coniditons on ng-class


I have a using an ng-repeat. The also has a ng-class true/false condition which is working. Am i able to add another condition to my true/false statement?

<tr ng-repeat="data in myData" ng-class="{true: 'green', false: 'red'}[data.IsPositive]">
    <td>
        {{data.Name}}
    </td>
    <td>
        {{data.CompanyName}}
    </td>
    <td>
        <span ng-show="data.Date | lessThanOneYear">Less than one year</span>
        <span ng-show="data.Date | lessThanOneYear">Greater than one year</span>
    </td>
</tr>

Essentially, i want to perform a check on if:

ng-class="[data.IsPositive] and [data.Date | lessThanOneYear]

So, if both of the above are true, then apply CSS class green... If false, apply red.


Solution:

I've had to use a mixture of the 2 suggestions provided. Essentially the condition with the filter needs to be wrapped in (), so:

ng-class="[data.IsPositive && (data.Date | lessThanOneYear)]

Solution

  • By doing this, you need to understand that the expression between [] must evaluate to one of the indexes you specified in the associative array {true: 'green', false: 'red'}.

    Then any expression that evaluate to true or false can be used, any boolean expression in this case.

    [data.IsPositive and data.Date | lessThanOneYear]