Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS how to put both ng-class and CSS class

I have an element which has static CSS classes and dynamic classes which will be determined by a method, so how do I put them together?

I tried below code, but it does not work:

<div class="static-class" ng-class="{'dynamic-class': isEnabled()}"></div>

So as a workaround I did this:

<div ng-class="{'static-class': true, 'dynamic-class': isEnabled()}"></div>

But this is ugly, especially when there are many static classes.

EDIT
I found my first example works! Sorry for for this question.

like image 444
Shuping Avatar asked Jan 07 '14 06:01

Shuping


People also ask

Can I use both class and ngClass?

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.

Can we use ngIf and ngClass together?

Now you have learned the basics of Angular directives, including how to use ngIf, ngFor, ngClass, ngStyle, ngModel, and ngSwitch. You can combine them to create more complex user interfaces.

What is the difference between ngClass and NgStyle?

ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute. Following will be translated to class="deleted" when isDeleted variable is true.


1 Answers

Your first example should work:

<div class="static-class" ng-class="{'dynamic-class': isEnabled()}"></div>

Alternatively you can also use:

<div class="static-class ng-class: {'dynamic-class': isEnabled()};"></div>
like image 144
Emma Guo Avatar answered Oct 18 '22 04:10

Emma Guo