【问题标题】:Why does Angular rewrite the URL fragment #foo to #/foo and how to avoid that?为什么 Angular 将 URL 片段 #foo 重写为 #/foo 以及如何避免这种情况?
【发布时间】:2023-03-18 23:12:01
【问题描述】:

我有一个依赖于 URL 片段 #moved 的应用程序。一段 JS 代码将其拾取并提醒用户更新她的书签:

if (window.location.hash === '#moved') {
  window.location.hash = "";
  history.pushState('', document.title, window.location.pathname);
  show_notification();
}

现在测试失败了,因为在引入 Angular(稳定版本,1.0.8)之后,#moved 被重写为 #/moved。 (我将$location 注入到我的控制器中,但我不确定这是否是导致该行为的原因。)

我可以改变条件,但我很好奇为什么 Angular 会这样做以及如何避免它?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

对于我的用例,我既想使用 Angular 的路由,也想使用一些书签来滚动到内容。我最终为我的书签使用了一个指令,并单独留下了路由。

<ul>
   <li><a href="#" app-bookmark="body">Home</a></li>
   <li><a href="#" app-bookmark="#usage">Getting Started</a></li>
   <li><a href="#" app-bookmark=".examples .first">Examples</a></li>
</ul>

然后我使用了以下指令。这使用 jQuery 来创建平滑的滚动效果,但也可以轻松地使用 document.body.scrollTop 来代替 animate 函数。

app.directive('appBookmark', function() {
   return {
      restrict: 'A',
      compile: function(el, attr) {
         el.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $('body,html').animate({scrollTop: Math.max($(attr.appBookmark).offset().top-50, 0)});
        });
      }
   }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多