Add class dynamically to character-based values

I would like to add a class dynamically if the integer is positive or negative. I tried calling a function from HTML, but that doesn't seem to be the correct way. Below is my pluker.

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 by which characters (+/-) can be identified from HTML and resolved in the HTML itself.

+4
source share
3 answers

You should use ng-class as below:

 // 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 using the function, do a direct markup check:

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

Updated plunker

+2
source

You can add this as in angular

 ng-class="{'test': getValue(i) < 0}" <span ng-class="{'test': getValue(i) < 0}"> {{getValue(i)}} </span> 
+1
source

Add only one condition to JS:

 if( $("span").text().indexOf('+') != -1) { $("span").addClass("positiveClass"); } 

Look at the jsfiddle action

0
source

Source: https://habr.com/ru/post/1242784/


All Articles