How do you do a ternary with AngularJS (in the templates)?
It would be nice to use some in html attributes (classes and style) instead of creating and calling a function of the controller.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: Angular 1.1.5 added a ternary operator, so now we can simply write
If you are using an earlier version of Angular, your two choices are:
(condition && result_if_true || !condition && 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.,
$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:
An example of 1) was given above. Here is an example of 3, which I think reads much better:
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.,