0

I'm working in an application using angularJs and Bootstrap. I need to display the title of a 'scenario' but changing the Css depending on the status of the scenario and displaying a different icon.

In the beginning I tried this

<span class="text-success" data-ng-if="scenario.status=='success'"><i class="fa fa-check-circle"></i>Scenario {{scenario.title}}</span>
<span class="text-danger" data-ng-if="scenario.status=='fail'"><i class="fa fa-exclamation-circle"></i>Scenario {{scenario.title}}</span>
<span data-ng-if="scenario.status=='none'">Scenario {{scenario.title}}</span>

Which is working fine. But I would like to do it in a more proper way and avoid the duplication of the code so I would like to use ng-class, I have modified the code as following:

 <span ng-class="{text-success:scenario.status=='success' || text-danger:scenario.status=='fail'}">Scenario {{scenario.title}}
                        <i ng-class="{fa fa-check-circle:scenario.status=='success' || fa fa-exclamation-circle:scenario.status=='fail'}"></i>
                        </span>

However this way is not working and I don't see what is the problem. Could someone please help me?

Thank you!

1
  • || syntax is wrong, you need an angular expression that return the classname Commented Jul 3, 2015 at 13:22

2 Answers 2

2

The correct solution is:

<span ng-class="{'text-success': scenario.status === 'success', 'text-danger': scenario.status === 'fail'}">
    Scenario {{scenario.title}}
    <i class="fa" ng-class="{'fa-check-circle': scenario.status === 'success', 'fa-exclamation-circle': scenario.status === 'fail'}"></i>
</span>

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.

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

Comments

0
$scope.getClassName = function() {
     return "text-" + scenario.status;      
}

Then binding:

ng-class="getClassName()"

1 Comment

i prefer to have logic in controller and not mixed in template, and this solution i more extensible to other kind of status

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.