Search code examples
cssangularjsng-class

Why doesn't ng-class work when simply providing a class name?


Fiddle.

I don't see anything to indicate why this shouldn't work. The Angular Doc says "If the expression evaluates to a string, the string should be one or more space-delimited class names." What am I doing wrong in this code?

Doesn't work:

 <div ng-class="myClass">
    Using ng-class (with no quotes so maybe it doesn't evaluate to a String).
</div>

Doesn't work:

<div ng-class="'myClass'">
    Using ng-class (with quotes around the class name so it is (?) evaluated to a String).
</div>

Works:

<div class="myClass">
    Using regular class, no ng-class.
</div>

Solution

  • ng-class is for dynamically adding/removing class(es) based upon conditions. I use class for your case above, but if you wanted to dynamically add a class foo use: ng-class="{'foo': condition}"

    The thing to remember is that angular is there to assist you to do dynamic things in-line with standard HTML. So if all you need to do is add a class to an element, just use class.