Last active
December 20, 2015 12:09
-
-
Save arnabdas/6129378 to your computer and use it in GitHub Desktop.
AngularJS ng-class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Update: Angular 1.1.5 added a ternary operator, so now we can simply write | |
| <li ng-class="$first ? 'firstRow' : 'nonFirstRow'"> | |
| If you are using an earlier version of Angular, your two choices are: | |
| (condition && result_if_true || result_if_false) | |
| {true: 'result_if_true', false: 'result_if_false'}[condition] | |
| item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value. | |
| E.g., | |
| <li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li> | |
| or | |
| <li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li> | |
| $first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop. | |
| With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following: | |
| a string of space-delimited class names | |
| an array of class names | |
| a map/object of class names to boolean values. | |
| An example of 1) was given above. Here is an example of 3, which I think reads much better: | |
| <li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li> | |
| The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added. | |
| ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g., | |
| <li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment