1

I'm new to Angular.js and I'm running into a problem. I'm using ng-repeat to iterate through a list of news items. Each item has a Title and Body, but will have an optional picture url that will be used as the background.

I can get the news item elements with picture URLs to display when there is a url present. See sample code below.

<li class="news-item col-md-6" ng-repeat="announcement in news.announcements | limitTo:8" ng-style="{'background-image': 'url({{announcement.Url}})'}">

I need to set the announcement.Url value to a default background picture URL when announcement.Url is NULL or Undefined. Not sure how I can go about this.

Any help would be much appreciated.

Thanks!

1 Answer 1

3
<li class="news-item col-md-6" ng-repeat="announcement in news.announcements | limitTo:8" ng-style="{'background-image': 'url({{announcement.Url || \'path to default image\'}})'}">

Anything between {{ and }} is an angular expression (similar to javascript itself as far as a beginner is concerned). You can simply include the || operator (a logical OR) and put the path to your default image in a string after that. If announcement.Url is null or undefined then it will be "falsy" and the latter half of the OR conditional will be used.

Edit: Notice that I escaped the string delimiters (\') because they are already nested inside a string that uses those delimiters.

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

2 Comments

Awesome! Thanks Alex. It actually worked without the escaping.
Oh Angular you sly dog ;)

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.