Complex angular js ng-class

Szymon Wygnański picture Szymon Wygnański · Nov 28, 2012 · Viewed 52.9k times · Source

I have the component and have a problem setting the css class to it. I want it to always have a class of "box", then to have additional classes specified by the directive "class" argument and one conditional class "mini".

Conceptually what I want to achieve is something like this:

<div class="box {{class}}" data-ng-class="{mini: !isMaximized}">
...
</div>

The problem is that when I set the class html attribute, the ng-class attribute is omitted. How to make my example work without changing the controller? Is it even possible, or should I set the class in the controller instead (which I wish to avoid)?

Answer

Andre Goncalves picture Andre Goncalves · Nov 28, 2012

A quick solution would be define the box class inside ng-class attribute:

<div data-ng-class="{mini: !isMaximized, box: true}"></div>

If you want to include a scope variable as a class, you can't use ng-class:

<div class="{{class}} box {{!isMaximized && 'mini' || ''}}">

Angular expressions do not support the ternary operator, but it can be emulated like this:

condition && (answer if true) || (answer if false)