Difference between “href” and “ng-href” in AngularJS

前端 未结 2 539
再見小時候
再見小時候 2021-02-05 04:21

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

相关标签:
2条回答
  • 2021-02-05 05:02

    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.

    0 讨论(0)
  • 2021-02-05 05:22

    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}}">Dynamic link</a>
    
      <br/>
    
      Change the link dynamically: <input type="text" ng-model="address">
    
    </div>
    

    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"/>Static link</a>
    
    0 讨论(0)
提交回复
热议问题