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.
well i would suggest you to check condition in your controller with a function returning true or false .
and in your controller check the condition
If you are using angular pre v1.1.5 (i.e. no ternary operator) and you still want an equivalent way to set a value in both conditions you can do something like this:
This will probably get downvoted to oblivion, but here is how I used 1.1.5's ternary operators to switch classes depending on whether a row in a table is the first, middle or last -- except if there is only one row in the table:
Check http://www.codinginsight.com/angularjs-if-else-statement/
The infamous angularjs if else statement!!! When I started using Angularjs, I was a bit surprised that I couldn’t find an if/else statement.
So I was working on a project and I noticed that when using the if/else statement, the condition shows while loading. You can use ng-cloak to fix this.
.ng-cloak { display: none }
Thanks amadou
If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:
Please note the old syntax with colon.
There is also a new better way of applying classes conditionally, like:
Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.
However these ways are not functionally equal. Here is an example:
We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.
This is in my work multiple conditionally judge: