Search code examples
angularjsng-classangularjs-http

ng-class class name which contains a scope variable rendered as null


I have a which utilizes classes based on a particular scope variable.

In this case, the scope variable is {{jobSingle.UserFit.Summary.score}} which takes on the values of -1 (when unknown) or 0-10 (when score is known).

The span is rendered with the following code.

<span ng-class="{true: 'fit-score-{{jobSingle.UserFit.Summary.score * 10}}', false: 'fit-score-unknown'}[jobSingle.UserFit.Summary.score > -1]">
    [Content]
</span>

However, the class is not populated correctly for when jobSingle.UserFit.Summary.score > -1.

When I inspect the element in the Developer Console, the code is displaying as such.

<span class="fit-score-null" ng-class="{true: 'fit-score-70', false: 'fit-score-unknown'}[jobSingle.UserFit.Summary.score > -1]">
    [Content]
</span>

The class that was rendered for the span was 'fit-score-null'.

Some other background info:

The above code used to work when I was using mock data defined locally.

However, after having switched my controllers to call live data from an API using $http, null started appearing in my class name for the above situation.

All other data apart from the above renders perfectly.

Am I doing something wrong? Many thanks in advance.


Solution

  • You should not evaluate (use {{ and }}) inside an angular version attribute since it will already evalutate the value - just like your write 'fit-score-' it will already evaluate that into a string. Try this instead

    ng-class="{true : 'fit-score-' + (jobSingle.UserFit.Summary.score * 10), false : ...