Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't {{}} work in src attributes? Why do I need ngSrc?

Tags:

angularjs

This works:

<a href="{{myAwesomeLink}}">It's a link. A dynamic one, at that.</a>

But this doesn't:

<img src="{{URLtoMyPerfectImage}}">

One needs to use ngSrc instead. May I know why this is the case? I had a similar problem getting a 'src' (or was it 'href'? I don't remember) to work in Handlebars.js and gave up on it (pressure for delivery).

Is this a pervasive browser issue or something similar?

like image 598
Aditya M P Avatar asked May 20 '13 11:05

Aditya M P


2 Answers

Extending the answer above me, while

<a href="{{myAwesomeLink}}">It's a link. A dynamic one, at that.</a>

works, it is not the best practice when dynamically creating links using Angular. Any time you use data binding in an anchor tag you should use the ng-href directive. So the code for the anchor tag should look like:

<a ng-href="{{myAwesomeLink}}">It's a link. A dynamic one, at that.</a>

Straight from Angular's documentation:

Using Angular markup like in an href attribute makes the page open to a wrong URL, if the user clicks that link before angular has a chance to replace the with actual URL, the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem.

This helps us understand ng-src: So with

<img src="{{imgPath}}">

The browser tries to load the image, but Angular has not yet replaced the bracketed expression within the src, so the image fails to load. By using

<img ng-src="{{imgPath}}">

you are telling the browser to wait to load the image until the bracketed expression has been filled in, thus loading the correct image.

like image 124
drdalton Avatar answered Oct 14 '22 15:10

drdalton


The documentation mention this

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

If you think carefully, the javascript databinding to your html happens after the html DOM is loaded, so the browsers sees the intial src as {{url}} rather that a valid url string and fails.

like image 40
Chandermani Avatar answered Oct 14 '22 14:10

Chandermani