加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 使用ng-include保留传统锚定行为

发布时间:2020-12-17 07:32:19 所属栏目:安全 来源:网络整理
导读:我不是在构建单页应用程序,而是在某些地方使用AngularJS的“传统”站点.我遇到了以下问题(使用1.3.0-beta.6): 标准的工作锚链: a href="#foo"Link text/a... [page content]a id="foo"/ah1Headline/h1[more content] 这很好.现在我在某处介绍一个模板部分
我不是在构建单页应用程序,而是在某些地方使用AngularJS的“传统”站点.我遇到了以下问题(使用1.3.0-beta.6):

标准的工作锚链:

<a href="#foo">Link text</a>
... [page content]
<a id="foo"></a>
<h1>Headline</h1>
[more content]

这很好.现在我在某处介绍一个模板部分:

<script type="text/ng-template" id="test-include.html">
  <p>This text is in a separate partial and inlcuded via ng-include.</p>
</script>

通过以下方式调用:

<div ng-include="'test-include.html'"></div>

部分包含正确,但锚链接不再起作用.单击“链接文本”现在将显示的URL更改为/#/ foo而不是/#foo,页面位置不会更改.

我的理解是使用ng-include隐式告诉Angular我想使用routes系统并覆盖浏览器的本机锚链接行为.我已经看到通过将我的html锚链接更改为#/#foo来解决此问题的建议,但由于其他原因我无法做到这一点.

我不打算使用路由系统 – 我只想使用ng-include而不会弄乱浏览器行为.这可能吗?

My understanding is that using ng-include implicitly tells Angular
that I want to use the routes system and overrides the browser’s
native anchor link behavior. I’ve seen recommendations to work around
this by changing my html anchor links to #/#foo,but I can’t do that
for other reasons.

路由系统是在一个单独的模块ngRoute中定义的,所以如果你没有自己注入它 – 而且我很确定你没有 – 它完全无法访问.

这个问题在某种程度上是不同的.

ng-include取决于:$http,$templateCache,$anchorScroll,$animate,$sce.因此,使用ng-include启动所有这些服务.

调查最自然的候选人是$anchorScroll. $anchorScroll的代码似乎没有任何损害,但服务依赖于$window,$location,$rootScope. $location的616行说:

baseHref = $browser.baseHref(),// if base[href] is undefined,it defaults to ''

所以基本上,基本href设置为”,如果之前没有设置的话.

现在看HERE – from BalusC answer:

As to using named anchors like,with the tag
you’re basically declaring all relative links relative to it,
including named anchors. None of the relative links are relative to
the current request URI anymore (as would happen without the
tag).

如何缓解这个问题?

我今天没有太多时间,所以不能自己测试,但我会尝试检查作为第一个选项是挂钩到‘$locationChangeStart’事件,如果新的URL是#xxxxxx类型只是防止默认行为并滚动与$anchorScroll替代原生方法.

更新

我认为这段代码应该做的工作:

$scope.$on("$locationChangeStart",function (event,next,current) {

    var el,elId;

    if (next.indexOf("#")>-1) {
        elId = next.split("#")[1];
        el = document.getElementById(elId);
        if(el){
           // el.scrollIntoView(); do not think we need it
           window.location.hash = "#" + elId;
           event.preventDefault();
        }    
    }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读