0

In my templates i am able to display an image from my data using

ng-style="{'background-image':'url({{f.flower.imageURL}})'}"

The imageURL always returns a hi-res image with URL such as

https://s3.amazonaws.com/images/FlowerImages/Rose_1920.jpg

However the endpoint also has smaller images such as

https://s3.amazonaws.com/images/FlowerImages/Rose_320.jpg
https://s3.amazonaws.com/images/FlowerImages/Rose_480.jpg
https://s3.amazonaws.com/images/FlowerImages/Rose_1024.jpg

How would i create a directive to traverse back through the URL up to the underscore and pass in a size i want (depending on the view) to update between the underscore and the .jpg?

1
  • numerous ways to do this in conjunction with your {{}} expression... controller function or custom filter are two that come to mind. {{getImage(f.flower.imageURL)}} for example. Then use another variable to toggle size condition Commented May 15, 2016 at 3:36

1 Answer 1

1

Based on you example, I don't think you need a directive. Just add a function to your controller.

Instead of

ng-style="{'background-image':'url({{f.flower.imageURL}})'}"

do

ng-style="{'background-image':'url({{generateImageUrl(f.flower.imageURL, 320)}})'}"

And your controller would have standard javascript to manipulate the url:

function generateImageUrl(url, size) {
  var n = url.lastIndexOf("_");
  var beforeUnderscore = url.substring(0, n);
  var afterUnderscore = url.substring(n+1);
  var suffix = afterUnderscore.split('.')[1];

  return beforeUnderscore + "_" + size + "." + suffix;
}

The same function could work for image as well

<img ng-src="{{generateImageUrl(f.flower.imageURL, 320)}}">

Note: ng-src is used instead of src to prevent the browser from requested the url before angular has bootstrapped.

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

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.