Complex angular js ng-class

2019-01-31 07:00发布

问题:

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

回答1:

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>


回答2:

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)



回答3:

Edit: for newer versions of Angular see Nitins answer as it is the best one atm

For me, this worked (I'm working on AngularJS v1.2.14 at the moment so I guess 1.2.X+ should support this, not sure about the earlier versions):

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

I replaced your {{class}} with {{myScopedObj.classesToAdd}} to show that any scoped variable or even a bit more complex object can be used this way.

So, every DIV element crated this way will have "box" class and any class contained within myScopedObj.classesToAdd (useful when using ng-repeat and every element in the array needs to have a different class applied), and it will have the "mini" class if !isMaximized.



回答4:

Another way to do this without double curly braces and includes scope variables, tested with angular v1.2+.

<div ng-class="['box', 
                aClass, 
               {true:'large': false: 'mini'}[isMaximized]]"></div>

It's also rather nice because the variable can use different types as a index without increasing complexity using ternaries. It can also remove any need for negations ;) Here is a fiddle link



回答5:

You can use simple expression given below

ng-class="{'active' : itemCount, 'activemenu' : showCart}"