6

I'm using AngularJS v1.2.9.

Inside ng-repeat, how do i use check the value of object and do action based on condition?

In English, something like:

if `X` is not null, then show `X`. Is it possible?

Here's my ng-repeat skeleton:

<li ng-repeat="r in results">
    <div>{{ r.title }}</div>
    <div>{{ r.location }}</div>
    <!--
    if ( r.date!=="null" ) {
        <div>{{ r.date }}</div>
    } else {
        <div>Date not confirmed yet.</div>
    }
    -->
</li>

I need to show r.date if it is not null. If it is null, then i say something else.

Please kindly help. Thanks all.

3 Answers 3

12
<li ng-repeat="r in results">
  <!-- If r.date contains a value, show it -->
  <span ng-if="r.date">{{r.date}}</span>
  <!-- If r.date does not contain a value show placeholder text -->
  <span ng-if="!r.date">Date not confirmed yet.<span>
</li>

Also see What does an exclamation mark before a variable mean in JavaScript

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

2 Comments

I liked @PankajParkar's bind more. But as he says, if the placeholder text/content gets large using different tags would probably be preferred.
Yes.. that was good.. I mentioned your answer because you had already wrote it & don't wanted to repeat that again..
3

Update

Question wasn't much clear so here is what you wanted just by having ng-bind directive in place. If the content is bigger then you can switch to the way suggested by @JustOneMoreQuestion below.

<li ng-repeat="r in results" ng-if="r.date">
    <div ng-bind="r.date ? r.date : 'Date not confirmed yet.'"></div>
</li>

You could easily do by using ng-if

<li ng-repeat="r in results" ng-if="r.date">
    <!--
    if ( r.date!=="null" ) {
        {{ r.date }}
    }
    -->
</li>

OR go for a filter which will filter out those will create a collection of element which has date in it.

<li ng-repeat="r in results| filter: { date: '' }">
    <!--
    if ( r.date!=="null" ) {
        {{ r.date }}
    }
    -->
</li>

2 Comments

Thanks for great help! But it is a bit misunderstood from what i want. (Sorry for that) I edited the question just now. Thank you :)
@夏期劇場 look at my edit, let me know if still im missing something
2

Check this one,

<li ng-repeat="r in results" >
    <div data-ng-if="r.date !== 'null'">
        Your Date
    </div>
    <div data-ng-if="r.date == 'null'">
        Date not confirmed yet
     </div>
 </li>

2 Comments

forgot to remove ' single quote.. you can use data-ng-if="r.date !== null". like this
data-ng-if="r.date" is enough

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.