11

I have a simple ng-repeat that displays a list of scores and a value of either Positive or Negative.

What i am trying to do is when the value is Negative, display a red background CSS class, and when Positive, display a green CSS class. However, for some reason, i am always seeing the red CSS class on my page.

HTML:

<tr ng-repeat="scores in Test" ng-class="{true: 'warning', false: 'ok'}[scores.Indicator == 'Negative']">                       
     <td>Overall: {{ scores.Indicator }}</td>
</tr>

CSS:

.warning {
    background: red;
}

.ok {
    background: green;
}
Oam Psy
  • 8,555
  • 32
  • 93
  • 157

1 Answers1

31

I haven't seen that particular syntax used before, what's the rationale behind {true: 'warning', false: 'ok'}[scores.Indicator == 'Negative']?

The way I would use ngClass here is

<tr ng-repeat="scores in Test" ng-class="{warning: (scores.Indicator == 'Negative'), ok: (scores.Indicator != 'Negative')}">

Does that work?

For better readability you could delegate it to the controller as well

<tr ng-repeat="scores in Test" ng-class="scoreClass(scores)">

$scope.scoreClass = function(scores) {
    return scores.Indicator == 'Negative' ? 'warning': 'ok';
}

Or you could create a directive

<tr ng-repeat="scores in Test" score-class scores="scores">

.directive('scoreClass', [function() {

    return {
        restrict: 'A',
        scope: {
            scores: '=',
        },
        link: function(scope, element, attrs, controller) {
            scope.$watch('scores', function() {
                element.removeClass('ok');
                element.removeClass('warning');
                if (scope.scores.Indicator == 'Negative') {
                    element.addClass('warning');
                } else {
                    element.addClass('ok');
                }
            }, true);
        }
    };
}]);
ivarni
  • 17,658
  • 17
  • 76
  • 92
  • The rational is behind Solution 2 in the answer here: http://stackoverflow.com/questions/15397252/angularjs-toggle-class-using-ng-class Using your answer, my rows are now all green (even for the Negative ones) – Oam Psy May 20 '14 at 14:35
  • Hmm.. that's interresting, I wonder if your original approach would work with `"{true: 'warning', false: 'ok'}[(scores.Indicator == 'Negative')]`? (e.g wrapping the logical test in the square brackets with parentheses) – ivarni May 20 '14 at 14:40
  • @OamPsy Well, now I'm confused. I pasted your HTML into a plnkr and it worked fine. http://plnkr.co/edit/p5rLB6cjNrTPVkWDnw9A?p=preview – ivarni May 20 '14 at 14:46
  • as mentioned above, i had a syntax error, your solution works – Oam Psy May 20 '14 at 14:47