ng-Class - multiple conditions and classes

Diogo Barroso picture Diogo Barroso · Jan 28, 2015 · Viewed 14k times · Source

I have been looking for examples of multiple conditions in ng-class but I can't find using the same terminology. Here is an example of what I want to achieve.

ng-class="isSelected ? 'side_menu_link_active' : 'side_menu_link_disabled' , pageSelected =='lectures' ? 'link_active' : 'link_disabled'"

Does anyone knows the correct syntax for this? thanks.

Answer

SoluableNonagon picture SoluableNonagon · Jan 28, 2015

If you want multiple conditions the syntax is:

ng-class=" {className: valueToCheckForTruthiness, otherClassName: otherValue  } " 

Example using your class names:

ng-class="{side_menu_link_active: isSelected, side_menu_link_disabled: !isSelected, link_active: pageSelected == 'lectures', link_disabled: pageSelected != 'lectures'   }"

You can take this further and generate an object using a function:

$scope.classGenerator = function(isSelected, pageSelected){
     var obj = {};
     isSelected ? obj.side_menu_link_active=true : obj.side_menu_link_disabled = false;
     pageSelected == 'lectures' ? obj.link_active = true : obj.link_disabled = false;
     return obj;
}
ng-class="classGenerator(isSelected, pageSelected)"