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>

3 Answers 3

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' }}

Sign up to request clarification or add additional context in comments.

6 Comments

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.
Angular introduced ternarys in 1.1.5. See here - stackoverflow.com/questions/12008580/…
Just wondering, is there any potential problems using an unescaped '&' in HTML? Might the browser produce validation errors before angular renders the templates?
@kapace , did you find an answer to your comment?
@Eric, No, I have just ignored this issue, but it gets highlighted by my editor as a problem.
|
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>

1 Comment

That's exactly the bloated solution I was afraid of... :(
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.