3

If you're at a location like this...

http://www.domain.com/index.html

... and you have a link that points to the same location...

<a href="/index.html">My Link</a>

... then clicking on the link does nothing. Normally you would be redirected to the page as normal; a handy way to refresh the page (without doing a full refresh).

I've traced the culprit of this odd behaviour to AngularJS.

Observe the following example:

<body>
    <a href="">Sample Link</a>

    <script>
        var SampleApp = angular.module("SampleApp", []);
    </script>
</body>

http://jsfiddle.net/7vqD9/

By clicking on the link the browser tries to go to the same location (because of a blank href). This is normal.

Now let's activate Angular:

<body ng-app="SampleApp">
    <a href="">Sample Link</a>

    <script>
        var SampleApp = angular.module("SampleApp", []);
    </script>
</body>

http://jsfiddle.net/7bEp3/

Clicking on the link does nothing.

Why does AngularJS break links in this way? Is there any obvious reason that I'm missing?

Rowan Freeman
  • 15,724
  • 11
  • 69
  • 100

2 Answers2

9

Why does Angular prevent classic behavior of href?

From Mastering web component with AngularJs:

AngularJS comes pre-bundled with the a directive, which prevents default actions on links when the href attribute is omitted. This allows us to create clickable elements using the a tag and the ng-click directive. For example, we can invoke the atag as follows:

<a ng-click='showFAQ()'>Frequently Asked Questions</a>

Having the a tags without a default navigation action is handy, as several CSS frameworks use the a tags to render different types of visual elements, where a navigation action doesn't make much sense. For example the Twitter's Bootstrap CSS framework uses the a tags to render headers in tabs and accordion components.

Keyword to retain is: "handy"

Mik378
  • 21,881
  • 15
  • 82
  • 180
1

Angular overrides the a tag: https://github.com/angular/angular.js/blob/master/src/ng/directive/a.js

The lines to note here are:

      // if we have no href url, then don't navigate anywhere.
      if (!element.attr('href')) {
        event.preventDefault();
      }

Angular does this because of ngHref, which sets the href only after angular and scope are fully loaded, thus preventing the user from accidentally going to /{{pageUrl}}/.

If you want to reload the page, you should look at the $location service provided by Angular.

musically_ut
  • 34,028
  • 8
  • 94
  • 106