Add some classes with an ng class where one of the classes is conditional

I got this code:

ng-class="{selectedHeader: key == selectedCol}" 

It works, but I would also like to add the value "key" as a class, Ive tried:

 ng-class="[{selectedHeader: key == selectedCol}, key]" 

But this will not work, does anyone know how to solve this?

+6
source share
7 answers

If you always want to add key as a class:

 ng-class="{selectedHeader: key == selectedCol, key: true]" 

or you can just put it in the class attribute with interpolation {{}} .

 ng-class="{selectedHeader: key == selectedCol}" class="{{key}}" 

Just for completeness, if you want to include it if it is selectedCol :

 ng-class="{selectedHeader: key == selectedCol, key: key == selectedCol}" 
+3
source

You can handle this with the $scope methods to determine the names of dynamic classes. It will look something like this:

Controller:

 $scope.selectedCol = 3; $scope.key = 3; // dynamic ng-class values $scope.selectedHeader = function () { if ($scope.selectedCol === $scope.key) return 'header-selected'; else return false; }; // selected header definition for ng-class $scope.headerKey = function () { return 'header-' + $scope.key; }; 

View:

 <header ng-class="[ selectedHeader(), headerKey() ]"> <h1>Header element</h1> </header> 

Result:

 <header ng-class="[ selectedHeader(), headerKey() ]" class="header-selected header-3"> <h1>Header element</h1> </header> 
+3
source

 // single class <div ng-class="{'myclass' : condition}"> </div> // multiple class <div ng-class="{'myclass1': condition1, 'myclass2': condition2}"> some content </div> 
+2
source

You can do it with

  ng-class="{selectedHeader: key == selectedCol}" class="{{key}}" 
+1
source

I think you are looking for: ng-class="{ {{key}}:{{key}} }"

Also keep in mind that css classes should not start with a number, so you may need to prefix your key value.

+1
source

Try the following:

 class="{{key}} ng-class:{'selectedHeader': key == selectedCol}; 
0
source

This will not work because {selectedHeader: key == selectedCol} will be evaluated as an object, not as a string:

 ng-class="[{selectedHeader: key == selectedCol}, key]" 

The following code works, it will add the selectedHeader classes and key value:

 ng-class="[key == selectedCol ? 'selectedHeader' : '', key]" 
0
source

All Articles