Ternary operator in AngularJS templates

Multi tool use
Ternary operator in AngularJS templates
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.
7 Answers
7
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 || !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.,
<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:
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>
If I could I would upvote you again for updating the question!
– Narretz
May 29 '13 at 11:44
I'll take care of it, @Narretz.
– Ian Hunter
Jun 6 '13 at 20:26
In the object-key accessing example, you can skip the 'false' key as it's anyways empty string.
– 0xc0de
Jul 22 '13 at 12:41
Word of warning, 1.1.5 is not currently stable.
– Adam Grant
Oct 3 '13 at 19:56
What if the conditional changes when your model is updated? I'd like the
ng-style
to update, but it seems to only be evaluated when the element is first rendered. (Angular noob here)– Hartley Brody
Oct 9 '13 at 0:42
ng-style
Update: Angular 1.1.5 added a ternary operator, this answer is correct only to versions preceding 1.1.5. For 1.1.5 and later, see the currently accepted answer.
Before Angular 1.1.5:
The form of a ternary in angularjs is:
((condition) && (answer if true) || (answer if false))
An example would be:
<ul class="nav">
<li>
<a href="#/page1" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Goals</a>
</li>
<li>
<a href="#/page2" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Groups</a>
</li>
</ul>
or:
<li ng-disabled="currentPage == 0" ng-click="currentPage=0" class="{{(currentPage == 0) && 'disabled' || ''}}"><a> << </a></li>
Weird. That's not very intuitive. I wonder why it was implemented this way.
– Ben Lesh
Aug 17 '12 at 15:49
Ternary was never implemneted, but this is just using the binary operators the way they work.
– Andrew Joslin
Aug 17 '12 at 20:09
@blesh, AngularJS promotes testability. Templates should not contain any logic. A ternary operator in a template should be refactored to a function call to the controller, for better testability.
– Marcello Nuccio
Aug 18 '12 at 7:18
@arg20 you should use ngClass directive (or ngClassEven and ngClassOdd). Then put all the logic for choosing css classes in the controller. This is much more easy to test automatically.
– Marcello Nuccio
Apr 10 '13 at 8:54
@arg20 I said to put it in the controller, not in the model. This should not be a problem. However, the documentation says: "The result of the evaluation can be a string representing space delimited class names, an array, or a map of class names to boolean values". Meaning that you can use "{ cssclass: someBoolCheck() }" as an expression, i.e. you put the css class in the view, and the logic in the controller. Look at this jsFiddle for an example.
– Marcello Nuccio
Apr 10 '13 at 14:36
For texts in angular template (userType
is property of $scope, like $scope.userType):
userType
<span>
{{userType=='admin' ? 'Edit' : 'Show'}}
</span>
By now we all found out version 1.1.5 comes with a proper ternary in the $parse
function so just use this answer as an example of filters:
$parse
angular.module('myApp.filters', )
.filter('conditional', function() {
return function(condition, ifTrue, ifFalse) {
return condition ? ifTrue : ifFalse;
};
});
And then use it as
<i ng-class="checked | conditional:'icon-check':'icon-check-empty'"></i>
I came to this question for the ternary operator but at the end I went with a filter and it felt really good... =D
– slacktracer
Oct 30 '13 at 17:57
There it is : ternary operator got added to angular parser in 1.1.5! see the changelog
Here is a fiddle showing new ternary operator used in ng-class directive.
ng-class="boolForTernary ? 'blue' : 'red'"
While you can use the condition && if-true-part || if-false-part
-syntax in older versions of angular, the usual ternary operator condition ? true-part : false-part
is available in Angular 1.1.5 and later.
condition && if-true-part || if-false-part
condition ? true-part : false-part
<body ng-app="app">
<button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'" class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
Take Quiz
Start Quiz
</div>
</body>
Button toggle and change header of button and show/hide div panel. See the Plunkr
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
I use a filter for this
– Jan
Jan 16 '13 at 12:49