Friday, March 29, 2019

css - What is the best way to conditionally apply a class?



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.


Answer



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:



ng:class="{true:'selected', false:''}[$index==selectedIndex]"



Please note the old syntax with colon.



There is also a new better way of applying classes conditionally, like:



ng-class="{selected: $index==selectedIndex}"


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:



ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"


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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...