Encountered issues arise when adding classes within table elements while having a class already applied to the entire table (such as a color applied to odd rows
<myClass tbody tr:nth-child(even) td>
). Upon inspecting the element using
Developer Tools, it appears that no styles are assigned in
element.style
. To address this, instead of utilizing
ng-class
, I opted for
ng-style
, where the new CSS attribute is visible inside
element.style
. Here's the code snippet that proved effective for me:
<tr ng-repeat="element in collection">
[...amazing code...]
<td ng-style="myvar === 0 && {'background-color': 'red'} ||
myvar === 1 && {'background-color': 'green'} ||
myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>
[...more amazing code...]
</tr>
Myvar undergoes evaluation, determining the style to be applied to each <td>
based on the value of myvar, overwriting the existing style applied by the CSS class for the entire table.
UPDATE
To apply a class to the table under specific conditions, such as upon visiting a page or other scenarios, you can utilize this structure:
<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">
The key to activating an ng-class lies in specifying the class to apply along with a true or false statement. A true value applies the class, while false does not. In this example, two route checks are made with an OR between them, ensuring that if we are in either /route_a
or route_b
, the active class will be applied.
This approach functions based on a logic function that returns either true or false.
In the initial example, ng-style is conditioned by three statements. If all are false, no style is applied. However, at least one statement will evaluate to true, leading to the application of the corresponding style. As any non-empty array equates to true, the resulting array will have only one true value, ultimately applying the remaining style due to the usage of OR in the overall response.
Additionally, let me provide you with the isActive() function:
$rootScope.isActive = function(viewLocation) {
return viewLocation === $location.path();
};
NEW UPDATE
Here's a handy tip for applying a class based on a variable's value, like displaying different icons depending on the content within a div
. The following code proves beneficial, especially in ng-repeat
situations:
<i class="fa" ng-class="{ 'fa-github' : type === 0,
'fa-linkedin' : type === 1,
'fa-skype' : type === 2,
'fa-google' : type === 3 }"></i>
Icons sourced from Font Awesome