Search code examples
javascripthtmlangularjsng-class

Add class dynamically to values based on symbols


I wanted to add class dynamically if the integer is positive or negative.. I tried by calling a function from the HTML but that dosen't seem to be a right way. Below is my plunker..

Add class from html

<div ng-repeat="i in test">
    <span class="test">  {{getValue(i)}} </span> 
</div>

I would like to know if there is any way wherin the signs(+/-) can be identified from the HTML and resolve them in the HTML itself..


Solution

  • You should use ng-class like follows :

    // JS
    $scope.isPositive = function(value) {
        return value.indexOf('-') == -1;
    }
    

    And

    // HTML
    <style>.green { color: green; } .red { color: red; }</style>
    <!-- ... --> 
    <span ng-class="isPositive(i) ? 'green' : 'red'">  {{getValue(i)}} </span> 
    

    Working Plunker

    EDIT

    To avoid use of the function, do the check in markup directly :

    <span ng-class="i.indexOf('-') == -1 ? 'green' : 'red'">  {{getValue(i)}} </span> 
    

    Updated plunker