0

I am new to Angular and I would like to know how to do something similar to an if statement.

I am using ionic to build my web app and have an xml feed coming in with a thumbnail which is shown like this "{{post.thumbnail}}"

Here is what I tried to do to show an alternative image if the image is empty.

<div ng-hide="{{post.thumbnail}} == null">
  <img src="{{post.thumbnail}}" width="100" height="100" alt=""/>
</div>
<div ng-hide="{{post.thumbnail}} != null">
  <img src="img/dining.jpg" width="100" height="100" alt=""/>
</div>

3 Answers 3

1

You could use ng-if:

<div ng-if="post.thumbnail">
  <img ng-src="{{post.thumbnail}}" width="100" height="100" alt=""/>
</div>
<div ng-if="!post.thumbnail">
  <img src="img/dining.jpg" width="100" height="100" alt=""/>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1
<div ng-hide="post.thumbnail == null"><img src="{{post.thumbnail}}" width="100" height="100" alt=""/></div>
<div ng-hide="post.thumbnail != null"><img src="img/dining.jpg" width="100" height="100" alt=""/></div>

3 Comments

Thanks, while most of the comments work, this is the most practical and what I was looking for. Tx! Btw I ended up getting rid of the div's and use the ng-hide in the image tags :)
@Jason:Use === and !== for comparison in js
@Muhsin Use the extra = if it is required to compare including type
0

You can use ng-if OR ng-show/hide. OR Another approach could be to do if-else in Controller. This will also avoid duplication of <div> if there are more than one condition to be checked.

Controller:

if $scope.post.thumbnail != null {
  $scope.imageSrc = $scope.post.thumbnail
} else {
   $scope.imageSrc = 'img/dining.jpg'
}

and in template:

<div><img src="{{imageSrc}}" width="100" height="100" alt=""/></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.