1

I notices that when I mix ng-class with class + expression (class="something-{{ stuff }}") which might not be set, the ng-class is not getting compiled.

Example:

This will work OK (JSFIDDLE)

<div 
     ng-controller="MainCtrl" 
     ng-class="(data.size > 10) ? 'font-large' : 'font-small'"
     >
     Lorem ipsum dolor sit amet

But when I use ng-class & class with expression (which does not exist on the scope) it will not work, it will not run/compile ng-class. (JSFIDDLE):

<div
    ng-controller="MainCtrl"
    class="just-a-class color-{{ data.color }}"
    ng-class="(data.size > 10) ? 'font-large' : 'font-small'"
    >
    Lorem ipsum dolor sit amet.
</div>

Is there any way to use both ng-class and class with expression or what is the workaround? Any suggestions much appreciated.

5
  • the second jsfiddle works, what am I missing here? Commented Sep 16, 2014 at 9:08
  • Your second jsfiddle works fine for me. The divs classes in Chrome Version 37.0.2062.120 (64-bit): just-a-class color-red font-small Commented Sep 16, 2014 at 9:08
  • I've done tidy-up and looks like is working OK now, I try to reproduce one more time. Commented Sep 16, 2014 at 9:13
  • Another way jsfiddle.net/satpalsingh/647792as just modified your second working fiddle Commented Sep 16, 2014 at 9:15
  • @kasoban I was able to reproduce, the issues is visible when I try to bind something that does not exist on the scope, see fiddle Commented Sep 16, 2014 at 9:35

1 Answer 1

2

When you need to add a class with data binding or condition, use ng-class.

from angularjs's ng-class doc:

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

This version is working well (jsfiddle)

It uses only ng-class, with out the regular class

<div ng-controller="MainCtrl" 
    ng-class="{'font-large' : (data.size >= 10), 
                'font-small' : (data.size < 10),
                'color-{{ data.nothing }}' : color.nothing }">

    Lorem ipsum dolor sit amet
</div>

this way ng-class will process the 'color-{{data.nothing}}' only if data.nothing is true

Sign up to request clarification or add additional context in comments.

3 Comments

I think the issues is that ng-class is not getting compiled when the data.nothing does not exist. github.com/angular/angular.js/issues/9109
very nice example, I might move all of my class expression to the ng-class . What is best practice here?
yes, ng-class is designed for that. please accept answer if it helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.