如何使用AngularJS基于Json字符串响应应用条件CSS类?

时间:2015-03-30 15:35:24

标签: javascript css json angularjs

我想基于JSON响应应用css类,例如,如果响应是"低"我希望背景颜色为绿色并应用无线电低css类,如果响应是"中等"我想让背景颜色变黄。如何使用AngularJS来完成这项任务。

HTML

    <form kendo-validator="ratingValidator" name="processRatingForm" novalidate ng-cloak
        ng-controller="EditProcessRatingCtrl" class="border-box-sizing grids-fonts">
        <p class="status">{{PrcsratingValidationMsg}}</p>
        <div class="row">
            <div class="form-group col-md-6">
                <div>
                    <label class="control-label" for="processInherentRisk">Process
                        Inherent risk rating</label>
                </div>
                <div  id="processInhRisk"
                    ng-model-options="{ updateOn: 'blur' }" ng-model="processRating.inherentRiskRatingKey" class="radio-low" >{{processRating.inherentRiskRatingKey}}</div>
            </div>
            <div class="form-group col-md-6">
                <div>
                    <label class="control-label" for="finalOutcomeInherentRiskRatingKey">Process
                        Inherent risk Business Final</label>
                </div>
                <div id="irrFinalOutcome"
                    ng-model-options="{ updateOn: 'blur' }"
                    ng-model="processRating.finalOutcomeInherentRiskRatingKey" class="radio-medium">{{processRating.finalOutcomeInherentRiskRatingKey}}</div>
            </div>
</div
</form>

3 个答案:

答案 0 :(得分:0)

您可以使用ng-class指令。

<div ng-class="{processRating.inherentRiskRatingKey === 'low': 'radio-low'}" >{{processRating.inherentRiskRatingKey}}</div>

编辑:

<div ng-class="{processRating.inherentRiskRatingKey === 'low': 'radio-low', processRating.inherentRiskRatingKey === 'high': 'radio-high'}" >{{processRating.inherentRiskRatingKey}}</div>

答案 1 :(得分:0)

只需测试输出并将结果放在$scope变量中,然后在$scope声明中使用该ng-class变量。

<强> HTML

<div id="processInhRisk" ... ng-class="{processRating.isMedium: medium}">{{processRating.finalOutcomeInherentRiskRatingKey}}</div>

<强>的Javascript

$scope.processRating.isMedium = processRating.finalOutcomeInherentRiskRatingKey == 'medium';

<强> CSS

.medium { background-color: yellow; }

答案 2 :(得分:0)

只需将值传递给class(低,高)并在css中提及颜色。

HTML

<div id="processInhRisk" ng-model-options="{ updateOn: 'blur' }" ng-model="processRating.inherentRiskRatingKey" ng-class="{{processRating.inherentRiskRatingKey" >{{processRating.inherentRiskRatingKey}}</div>

CSS

.low{
color: bla bla bla
}
.high{
color: bla bla bla
}

确保您在json中正确获取颜色代码