应用ng类来计算P标记内的不同表达式

Apply ng-class to evaluate different expressions inside a P tag

本文关键字:表达式 ng 计算 应用      更新时间:2023-09-26

我想应用一个ng类来计算<标记

   <p <strong>LW$:</strong> {{d.lw_metric}} <strong>LW:</strong> {{d.lw_metric_percentage}} <strong>L4W:</strong> {{d.l4w_metric}}</p>              

我有我的CSS:

.positive{ color: green}
.negative{ color: red}

但我不知道如何告诉angular评估标签内的所有值,而不是像那样一个接一个地评估

ng-class = "{'positive':data.merchMetrics.LW_CHG_LY >=0,'negative':data.merchMetrics.LW_CHG_LY <0}"

因为我在这个标签里有五个表达式,所以我想有一些方法可以避免这种情况。

您可以简单地将该逻辑转移到控制器

ng-class="evaluateClass(data.merchMetrics)"

控制器

$scope.evaluateClass = function(merchMetrics){
    var returnClass = "";
    //below for loop will iterate through each property of object
    //and will decide the class need to apply
    for (var key in merchMetrics) {
       if (merchMetrics.hasOwnProperty(key)) {
          //you could also add the logic here
          //so that string will have positive & negative class once
          if(merchMetrics[key] > 0)
             returnClass = returnClass + "positive "
          else
             returnClass = returnClass + "negative "
       }
    }
    //you could return your class from here
    return returnClass;
};