Search code examples
javascriptcssangularjsng-class

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


I want to apply an ng-class to evaluate the negative values inside a < p > tag

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

I have my CSS:

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

But I don't know how tell angular to evaluate all the values inside the tag instead of doing one by one like this

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

Because I have five expressions inside this tag so I guess there's some way to avoid this.


Solution

  • You could simply shift that logic to controller

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

    Controller

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