Difference between "href" and "ng-href" in AngularJS

All we need is an easy explanation of the problem, so here it is.

I’ve used both href and ng-href and I couldn’t see the difference between them.

Why does Angular have the ng-href attribute, and when should I use it?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

From the documentation:

Using Angular markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before Angular has a chance to replace the {{hash}} markup with its value. Until Angular replaces the markup the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem.

Effectively, the only place you’re using it is for links in which you need to rely on a value provided to the DOM by Angular. If you do not require Angular for a part of that link, or you don’t plan on using Angular to generate that link, then you do not need to use ngHref.

Method 2

If you need to bind values from your model you use the directive. For example:

<div ng-init="address='http://stackoverflow.com/questions/37467603'">

  <a ng-href="{{address}}" rel="nofollow noreferrer noopener">Dynamic link</a>


  Change the link dynamically: <input type="text" ng-model="address">


In the example above, the value of address is programmatically bound to the value in the input text box, which you can change.

If you don’t need to be dynamic (i.e. react to a change in the model’s state), then you can simply stay with href:

<a href="http://stackoverflow.com/questions/37467603" rel="nofollow noreferrer noopener"/>Static link</a>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply