Applying ng-class based on value

China☆狼群 提交于 2019-11-29 03:54:05

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);
        }
    };
}]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!