Complex angular js ng-class

人盡茶涼 提交于 2019-11-29 20:53:56

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>
Andre Goncalves

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)

pootzko

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.

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

You can use simple expression given below

ng-class="{'active' : itemCount, 'activemenu' : showCart}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!