angular实现链接锚记

前言:

之所以这么说,是因为angular的路由将html默认的链接锚记的#给占用了,所以传统的链接锚记在这里将不再适用,这个有点坑啊,又要多写好几行代码来模拟这个功能。

实现原理:

location.hash()是用来设置页面的标识,在单页应用里因为所有页面都集成到一个页面中,通过路由来实现页面片段的加载,这就需要这个location.hash()来区分。

示例代码:

HTML:

1. 链接锚记触发元素:

<li ng-click="clickLog(item)" ng-repeat="item in HotSiteList">{{item.dataName}}</li>

2. 链接锚记目标元素:

<div ng-repeat="l in letters" ng-if="trainSitesList">
    <div class="site-panel-title padding-left graycolor" id="anchor{{l}}">{{l}}</div>
    ......

JS:

$scope.gotoAnchor = function(x) {
           $location.hash('anchor' + x);
    $anchorScroll();
}

如上,当点击列表项,触发gotoAnchor事件,就会跳转到对应id的div标签

原文地址:https://www.cnblogs.com/xyyt/p/6860155.html