我在页面上有指向锚点的链接(a href =“#idea”)。 ui-router 明显地覆盖了它们。 有没有一种方法可以和谐地使用两者?谢谢。
https://gist.github.com/anonymous/2880f2f2c9f91b0b695f#file-gistfile1-txt
href
上使用它,而是应该像以下方式添加:”<a href="" ng-click="gotoAnchor()">...</a>
$anchorScroll
API的更多信息请参见此处。<a ui-sref="routename({'#': 'ownerfeatures'})">Link</a>
嗨,我遇到了与锚点相关的类似问题。
由于我想继续使用常规的HTML语法(href =“#may-hash”),因此我编写了一个指令,它会检查链接是否为锚点,如果是,则执行滚动操作。请参见详细代码:
/**
* Ressource : https://docs.angularjs.org/api/ng/service/$anchorScroll
*/
.directive('a', ['$location', '$anchorScroll', function ($location, $anchorScroll) {
return {
restrict: 'E',
link: function (scope, elem, attrs)
{
// href should be defined and not empty
if(typeof attrs.href!=='undefined' && attrs.href.length > 0)
{
// href should be an anchor
if(attrs.href.substring(0, 1) === '#')
{
elem.on('click', function (e)
{
// if current hash is different from requested hash
// then set new hash
// no need to call $anchorScroll()
// since scroll is auto if you've not used $anchorScroll.disableAutoScrolling()
if ( '#' + $location.hash() !== attrs.href)
{
$location.hash(attrs.href);
}
// if hash is the same, force scroll
else
{
$anchorScroll();
}
});
}
}
}
};
}])
我知道这是一个老话题,但总是卡在寻找更好的解决方案来实现我的应用程序中的锚定。
今天我正在寻找在同一页中滚动并测试了许多不同的解决方案。大多数情况下,这个是一般推荐的解决方案:
<a ui-sref="routename({'#': 'ownerfeatures'})">Link</a>
这个问题是过渡到新状态并跳转到锚点时可以正常工作,但如果您想在同一页中滚动,则效果不佳,因为它仅适用于第一次点击。
然后我意识到使用$anchorScroll
对此非常有帮助,并制作了这个指令,可能会帮助某些人。请注意,我没有使用location.hash,因为我不想将哈希添加到我的地址栏,而且在我的流程中存在一些情况,当不需要时使屏幕滚动。
function anchorScroll($anchorScroll){
return {
restrict: 'A',
scope: {
target: '=anchorScroll'
},
link: function ( scope, element, attrs ) {
element.bind('click', function(event) {
console.log(scope.target)
$anchorScroll(scope.target);
})
}
}
}
但是也有一种非常简单的方法,只需在模板中使用$anchorScroll
。 在您的控制器中:
$scope.anchorScroll = $anchorScroll;
在视图中:
<a href="" ng-click="anchorScroll('nameOfTheAnchor')">Scroll to ID</a>
app.state1.child
上,并且您的锚点标签为#list
,那么假设您的a
标签使用此代码。<a ui-sref="app.state1.child#list">Link</a>