Applying ng-class based on value

前端 未结 1 1628
醉酒成梦
醉酒成梦 2020-12-16 17:26

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 Negativ

相关标签:
1条回答
  • 2020-12-16 18:09

    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);
            }
        };
    }]);
    
    0 讨论(0)
提交回复
热议问题