Angular bindings in href working but src binding not?

I am new to Angular and I am trying to learn about this through a tutorial on my own site.

Link to the step I am currently finding

Now what I understand from this particular step is that I can user href="#/phones/{{phone.id}}"

and Angular bind {{phone.id}}

on processing, but src

it needs the attribute to bind the attribute, ng-src

or else the browser will treat the markup {{ expression }}

literally.

Why src

doesn't Angular binding but href

does? Why don't we need ng-href

or something like this to make it work?

+3


source to share


3 answers


Because the browser is trying to load the image from the attribute src

while rendering the html page. So the first time the page is rendered, the browser will parse the expression as the image source and return a 404.

Angular does it with ng-src

resolving the image path and updating the attribute src

after evaluating the expression.



But in the case href

inside the anchor, it's just parsing the string, the browser shouldn't download anything. The attribute href

will be updated after the expression is evaluated and the browser will receive the change.

+2


source


Using Angular markup such as {{phone.id}} in the href attribute will cause the link to navigate to the wrong URL if the user clicks on it before Angular has the ability to replace the {{phone.id}} markup with its value. Before Angular replaces the markup, the connection will be broken and will most likely return a 404 error.

The ngHref directive solves this problem.

Wrong way to write:

<a href="#/phones/{{phone.id}}">Possibly broken phone</a>

      

Correct way to write:



<a ng-href="#/phones/{{phone.id}}">Working phone</a>

      

This is straight from the AngularJS docs https://docs.angularjs.org/api/ng/directive/ngHref

In your example img src should use ng-src since the image is loaded automatically by ASAP, the page starts loading and Angular has no way to replace it.

https://docs.angularjs.org/api/ng/directive/ngSrc

+1


source


From the ngSrc doc:

Using Angular markup such as {{hash}} in the href attribute will cause the link to navigate to the wrong URL if the user clicks on it before Angular has a chance to replace the {{hash}} markup with its value.

In fact, using href is an unsafe method.

But src waits for nothing, the browser receives the src during rendering - and throws an exception.

0


source







All Articles