Mohamed Yakout
Mohamed Yakout

Reputation: 3036

ng-src not working for local URL in public folder

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 ?

Upvotes: 0

Views: 652

Answers (1)

bri
bri

Reputation: 3030

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.

Upvotes: 1

Related Questions