Search code examples
javascriptangularjsternary-operatorng-class

Combining ternary operator and equality statements in ng-class


I have an element: <div ng-class="a ? 'class1' : 'class2'"></div> I need to add another ng-class statement to it ng-class="class3: b !== c". How do I combine the ng-class statements together. Neither <div ng-class="{a ? 'class1' : 'class2, class3: b !== c"></div> nor <div ng-class="(a ? 'class1' : 'class2') + ' ' + (class3: b !== c)"></div> seem to work. Please advise.


Solution

  • My preferred syntax for ng-class is the following, since it is explicit as to which classes you are adding, without using the ternary operator:

    <div ng-class="{'class1' : a, 'class2' : !a, 'class3': b !== c }"></div>
    

    If you want to use the ternary, you can do this:

    <div ng-class="(a ? 'class1' : 'class2') + ' ' + (b !== c ? 'class3': '' )></div>
    

    Your solutions didn't work because you tried to mix the 2 differents syntaxes (with and without curly brackets).