Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Js combine a fixed ng-class with an expression in same tag?

I have a tag:

<body ng-cloak class="foobar" ng-class="{'fixed-header': settings.isFixed}">

In another similar project I have a similar:

<body ng-cloak class="foobar" ng-class="routeClassName">

How can I apply both the routeClassName and the conditional class?

I have tried

<body ng-cloak class="foobar" ng-class="{'routeClassName','fixed-header': settings.isFixed}">

and similar, but it throws an error. So I guess my syntax is off....

like image 363
Steve Avatar asked Apr 22 '14 18:04

Steve


People also ask

Can we use class and NgClass together?

yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

How do you add NgClass based on condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

Can we use NGIF and NgClass together?

javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


1 Answers

Here are two ways to accomplish this:

First being, just have Angular interpolate the value since it is just the class name string anyway and then use ngClass for your conditional:

<body ng-cloak class="foobar {{routeClassName}}" ng-class="{'fixed-header': settings.isFixed}">

Second being, use true in the statement you have tried:

<body ng-cloak class="foobar" ng-class="{'routeClassName': true, 'fixed-header': settings.isFixed}">

I would lean toward the first option since ngClass is meant for conditional classes based on expressions.

like image 121
DRiFTy Avatar answered Oct 09 '22 13:10

DRiFTy