覆盖Angular UI-Router以便链接到页面锚点

3
5个回答

3
“你不应该这样在 href 上使用它,而是应该像以下方式添加:”
<a href="" ng-click="gotoAnchor()">...</a>

你可以在这里底部看到一个例子,关于$anchorScroll API的更多信息请参见此处

感谢您的回答,Bricktop。尽管您的解决方案在某种程度上有效,但如果我想将我的锚内容用作弹出窗口/模态框,而不使用$modal或UI bootstrap库,那该怎么办呢?在我看来,这仍然是一个让我难以理解的头疼问题。 - AllJs
我不确定我是否理解你的用例。如果你想向锚点和模态框提供内容,那么你可以通过控制器更轻松地将数据提供给两者。 - Bricktop

1
如果您想将ui-router与锚点标记结合使用,我使用以下代码解决了我的问题。
<a ui-sref="routename({'#': 'ownerfeatures'})">Link</a> 

0

嗨,我遇到了与锚点相关的类似问题。

由于我想继续使用常规的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();
                        }

                    });
                }
            }

        }
    };
}])

0

我知道这是一个老话题,但总是卡在寻找更好的解决方案来实现我的应用程序中的锚定。

今天我正在寻找在同一页中滚动并测试了许多不同的解决方案。大多数情况下,这个是一般推荐的解决方案:

<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>

0
更好的方法是这样做,假设您在状态app.state1.child上,并且您的锚点标签为#list,那么假设您的a标签使用此代码。
<a ui-sref="app.state1.child#list">Link</a>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接