Lets say you have an array that is rendered in a ul
with an li
for each element and a property on the controller called selectedIndex
. What would be the best way to add a class to the li
with the index selectedIndex
in AngularJS?
I am currently duplicating (by hand) the li
code and adding the class to one of the li
tags and using ng-show
and ng-hide
to show only one li
per index.
If you want to go beyond binary evaluation and keep your CSS out of your controller you can implement a simple filter that evaluates the input against a map object:
This allows you to write your markup like this:
partial
controller
My favorite method is using the ternary expression.
Note: Incase you're using a older version of Angular you should use this instead,
We can make a function to manage return class with condition
And then
You can refer to full code page at ng-class if example
I am new to Angular but have found this to solve my issue:
This will conditionally apply a class based on a var. It starts off with a icon-download as a default, the using ng-class, I check the status of
showDetails
iftrue/false
and apply class icon-upload. Its working great.Hope it helps.
Ternary operator has just been added to angular parser in 1.1.5.
So the simplest way to do this is now :