AngularJS Ng-class If-else Expression


Answer :

Use nested inline if-then statements (Ternary Operators)

<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')"> 

for example :

<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">     ... </div> 

And make sure it's readable by your colleagues :)


you could try by using a function like that :

<div ng-class='whatClassIsIt(call.State)'> 

Then put your logic in the function itself :

    $scope.whatClassIsIt= function(someValue){      if(someValue=="first")             return "ClassA"      else if(someValue=="second")          return "ClassB";      else          return "ClassC";     } 

I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/


I had a situation where I needed two 'if' statements that could both go true and an 'else' or default if neither were true, not sure if this is an improvement on Jossef's answer but it seemed cleaner to me:

ng-class="{'class-one' : value.one , 'class-two' : value.two}" class="else-class" 

Where value.one and value.two are true, they take precedent over the .else-class


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?