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

我不是在构建单页应用程序,而是在某些地方使用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();
        }    
    }
});

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...