If image is null from JSON, use another image - AngularJS

424 views Asked by At

Below I have an ng-repeat where the inner div gets a background image set after reading a JSON file.

My question is - If post.featured_image.attachment_meta.sizes.medium.url does not exist or is null, what would be the best approach to replace this with another image? Say a default backup image? A solution or tips to what to look for is what I am after as I am relatively new to AngularJS.

Code is below:

<article ng-repeat="post in posts">
   <div style="background-image: url({{ post.featured_image.attachment_meta.sizes.medium.url }})"></div>
</article>
1

There are 1 answers

0
michelem On BEST ANSWER

You can use ng-style:

<article ng-repeat="post in posts">
   <div ng-style="post.featured_image.attachment_meta.sizes.medium.url === null ? {'background-image': 'url(/yourimage.jpg)' } : {'background-image': 'url('+post.featured_image.attachment_meta.sizes.medium.url+')' }"></div>
</article>