3

I have an element containing a value from my controller:

<span>[[myvalue]]</span>

which I'd change the background color depending on the value. For example values 1-5 should have red and 6-10 should have green.

<span style='background-color: #green'>9</span>
<span style='background-color: #red'>1</span>

What is the simplest way to achieve this?

2 Answers 2

6

As tymeJV mentioned with ngStyle you can also use ngClass

<span ng-class="{'myClass' : (myValue < 9)}">{{myValue}}</span>

Also to promote some unit testing I would also recommend placing tho logic into a function so you can test easily as it also makes the markup a bit easier to read.

Markup

<span ng-class="{'myClass' : isSpecial(myValue)}">{{myValue}}</span>

Controller

$scope.isSpecial = function(value){ return myValue < 9};

Granted my example and yours is a bit contrived, but can help make things easier to maintain later on.

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

Comments

3

Here is an example using ngStyle

<span  ng-style="myStyle(myValue)"> {{myValue}} </span>

controller:

$scope.myStyle= function(value){
    return parseInt(value) > 5 ? {color: 'green'} : {color: 'red'}
}

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.