0

I've got an array of object where each has a color variable ('success', 'danger', 'info'). I have to apply them on panels, texts and buttons, just like that:

<div class="panel" ng-class="panel-{{panel.color}}"></div>
<button class="btn" ng-class="btn-{{panel.color}}"></div>
<p ng-class="text-{{panel.color}}"></p>

Of course, this solution doesn't work.

4
  • 2
    Did you try with class instead of ng-class ? Commented Mar 5, 2016 at 18:19
  • You're not using ng-class correctly, should read about ngClass API here: docs.angularjs.org/api/ng/directive/ngClass. Otherwise use ng-attr-class. Commented Mar 5, 2016 at 18:20
  • @Fieldset, your solution works. Make an answer, not a comment and I will approve it. Commented Mar 5, 2016 at 18:23
  • 1
    ng-class is useful if you want to add and remove classes dynamically, but if you just want to interpolate a variable use class. Commented Mar 5, 2016 at 18:24

2 Answers 2

3

1. Why it does not work ?

The reason why this code ng-class="panel-{{panel.color}}" doesn't work is that you are confusing ng-class directive which accepts variables names without doubles curly braces and class attribute which requires doubles curly braces around the variables names.

2. How to fix it ?

There are two ways to do it :

One way with ng-class :

<span ng-class="'panel-'+panel.color">panel {{panel.color}}</span>

Another one with class :

<span class="panel-{{panel.color}}">panel {{panel.color}}</span>

JsFiddle

3. ngClass directive is very handy

There are many ways to use ngClass.

You can pass an array of class names :

<span ng-class="['panel-'+panel.color, 'panel-'+panel.primary]">panel </span>

Or you can conditionally add classes :

<span ng-class="{'panel-red' : panel.isRed, 'panel-primary': panel.isPrimary}">panel</span>

Or use ternary operator :

<span ng-class="panel.isRed ? 'panel-red' : 'panel-not-red'">panel</span>
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use ngClass like this:

<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?

<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">

or

ng-class="x > 4 ? 'success' : 'danger'">

Instead of x >4 put your condition

Here you can find lot's of real examples: https://scotch.io/tutorials/the-many-ways-to-use-ngclass

Comments

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.