为什么AngularJS会破坏自引用锚链接?

3
如果你在这样的位置...
http://www.domain.com/index.html

......而且您有一个指向相同位置的链接......

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

如果单击链接没有任何反应,通常情况下您会像往常一样被重定向到页面;这是一种方便的刷新页面的方法(而不进行完全刷新)。

我已经追踪到这种奇怪行为的罪魁祸首是AngularJS。

请观察以下示例:

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

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

http://jsfiddle.net/7vqD9/

点击链接后,浏览器会尝试访问相同的位置(因为空白href),这是正常的。

现在让我们激活Angular:

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

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

点击链接没有任何反应

为什么AngularJS会这样破坏链接呢?有我忽略的明显原因吗?


2
https://dev59.com/F2Qo5IYBdhLWcg3wfPjK#16003013 应该能给你所需的答案。 - Nathaniel Johnson
1
完美。添加 target="_self" 就可以了。 - Rowan Freeman
@RowanFreeman 这就是我所做的。非常好用。 - frosty
2个回答

9

为什么Angular阻止了href的经典行为?

来自使用AngularJs掌握Web组件

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.

保留的关键词是:"handy"。

1
Angular 覆盖了 a 标签:https://github.com/angular/angular.js/blob/master/src/ng/directive/a.js 需要注意的行有以下几行:
      // if we have no href url, then don't navigate anywhere.
      if (!element.attr('href')) {
        event.preventDefault();
      }

Angular这样做是因为ngHref,它只在angular和作用域完全加载后设置href,从而防止用户意外进入/{{pageUrl}}/
如果您想重新加载页面,应查看Angular提供的$location服务。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接