0

I receive JSON Obj from request, and this Obj has image URL as the following:

$scope.userObj = {Name: "Jone", img_url: "../photos/profile"}

And I used ng-src to display it as the following:

<img ng-src="{{userObj.img_url}}" alt="" align="left">

But I see broken image, The weird thing if I write it directly using ng-src, as:

<img ng-src="../photos/profile" alt="" align="left">

it's working.

How can I fix it ? Why ng-src not working for local storage from JSON (dynamically), but work for local storage static URL ?

Mohamed Yakout
  • 2,868
  • 1
  • 25
  • 45
  • add {{userObj.img_url | json}} before the img element, in order to see if it is replaced with "../photos/profile" or not . (where is the extension ? ) – Pierre Emmanuel Lallemant Jan 18 '16 at 14:52
  • Actually without `| json` it's replace with `..photos/profile` .. But not working, so I see it's weird !!! – Mohamed Yakout Jan 18 '16 at 14:57
  • If you right-click on image in finished page, is the image src set to the value you'd expect? – bri Jan 18 '16 at 14:58
  • @bri Yes, It's set the value correct, and I see `ng-src="../photos/profile"` but not work .. If I set it hard coded, it's work ? – Mohamed Yakout Jan 18 '16 at 15:00
  • @Mohamed - Now, just curious... what is the exact name of the image you are attempting to test with... does it have an extension? I'm surprised it's working when you hardcode it since that doesn't really seem like a filename but I suppose there's nothing preventing you from naming it that way specifically :). – Marcidius Jan 18 '16 at 15:07

1 Answers1

1

Without a fiddler to play with, I have a feeling that you're being caught by $sce service in angular:

By default, Angular only loads templates from the same domain and protocol as the application document. This is done by calling $sce.getTrustedResourceUrl on the template URL. To load templates from other domains and/or protocols, you may either whitelist them or wrap it into a trusted value.

../photos/profile might be outside of that "trusted domain."

You could 'wrap' the url parameter into a trusted domain response. Take a look at this simple approach -- and note that the answer is NOT the one with the green check.

Use with Caution

Just as a quick word of warning -- this approach can lead to security problems if that URL source is, somehow, editable by a user and NOT validated by your back-end code. You're basically telling angular "relax -- this is a safe url" so you want to make sure that it IS, in fact, a safe url.

In general, don't use that trust filter on a url that your user provides, or that is pulled from your database/repo unless you have safeguards in place to avoid loading unsafe image content.

Community
  • 1
  • 1
bri
  • 2,932
  • 16
  • 17