Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex angular js ng-class

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

like image 871
Szymon Wygnański Avatar asked Nov 28 '12 14:11

Szymon Wygnański


2 Answers

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)

like image 104
Andre Goncalves Avatar answered Oct 09 '22 05:10

Andre Goncalves


I needed multiple classes where one was $scope derived and others were literal classes. Thanks to the hint from Andre, below worked for me.

<h2 class="{{workStream.LatestBuildStatus}}" 
    ng-class="{'expandedIcon':workStream.isVisible,  'collapsedIcon':!workstream.isvisible}">{{workStream.Name}}</h2>
like image 12
Nitin Arora Avatar answered Oct 09 '22 04:10

Nitin Arora