根据值应用 ng-class [英] Applying ng-class based on value

查看:26
本文介绍了根据值应用 ng-class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 ng-repeat,它显示一个分数列表和一个正值或负值.

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

我想要做的是当值为 Negative 时,显示红色背景 CSS 类,当值为 Positive 时,显示绿色 CSS 类.但是,出于某种原因,我总是在我的页面上看到 red CSS 类.

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;
}

推荐答案

我以前没见过使用过这种特定语法,{true: 'warning', false: 'ok'}[scores.Indicator == 'Negative']?

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

我在这里使用 ngClass 的方式是

The way I would use ngClass here is

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

那行得通吗?

为了更好的可读性,您也可以将其委托给控制器

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);
        }
    };
}]);

这篇关于根据值应用 ng-class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆