33

Is there any way to write logic inline in a template in AngularJS.

What I want to do is something like this:

<div ng-repeat="item in items">
    {{item.isValid ? 'Valid item' : 'Invalid Item'}}
</div>
Seb Nilsson
  • 26,200
  • 30
  • 103
  • 130

3 Answers3

76

You can use && and ||, which will end up working just like the ternary operators.

{{item.isValid && 'Valid' || 'Invalid' }}

EDIT: Angular introduced ternary operators in 1.1.5:

{{item.isValid ? 'Valid' : 'Invalid' }}

Community
  • 1
  • 1
Andrew Joslin
  • 43,033
  • 21
  • 100
  • 75
  • Beautiful! Exactly what I was looking for. They mention in the documentation that there can be "expressions" inside the curly-braces and now I understand better how to use them. Thanks. – Seb Nilsson Mar 14 '13 at 13:27
  • Angular introduced ternarys in 1.1.5. See here - http://stackoverflow.com/questions/12008580/a-ternary-in-angular-templates-angularjs/12151492#12151492 – BradGreens Dec 31 '13 at 15:26
  • Just wondering, is there any potential problems using an unescaped '&' in HTML? Might the browser produce validation errors before angular renders the templates? – kapace Dec 12 '14 at 01:03
  • @kapace , did you find an answer to your comment? – Eric Apr 03 '15 at 19:30
  • @Eric, No, I have just ignored this issue, but it gets highlighted by my editor as a problem. – kapace Apr 07 '15 at 18:58
  • Only a small point but took me a minute to figure it out, you're missing a single quote at the of Invalid, i.e. it should read: {{item.isValid ? 'Valid' : 'Invalid'}} – Starjumper Tech SL May 08 '15 at 11:37
0

You can insert a span with ng-show to show your conditional text

Example

<div ng-repeat="item in items">
    <span ng-show="item.isValid">
           Valid item
    </span>
    <span ng-show="!item.isValid">
           Invalid item
    </span> 
</div>
I_Debug_Everything
  • 3,776
  • 4
  • 36
  • 48
0

You can't use conditionals in angular expressions. And, if your div content is light (just text), you might want to use ng-bind (it also saves you from having additional span element):

<div ng-repeat="item in items" ng-bind="{true: 'Valid item', false: 'Invalid item'}[item.isValid]"></div>
Stewie
  • 60,366
  • 20
  • 146
  • 113