AngularJS$anchorScroll将##-锚名添加到页面URL中.我怎样才能避免这种情况

AngularJS $anchorScroll adds ##-anchorname to page URL. How can I avoid this?

本文关键字:能避免 情况 URL anchorScroll 添加 AngularJS      更新时间:2023-09-26

我正在使用AngularJS的locationhash() + $anchorScroll将选定的页面元素移动到窗口顶部,一旦其内容通过Ajax加载

.JS: 在控制器中:

     $scope.scrollTo = function (location) {
            //Scroll to category head
            $scope.categoryHead = "grouptitle-" + location;
            $location.hash($scope.categoryHead);
            $anchorScroll($scope.categoryHead);
     };

在指令中:

 .directive('onFinishRender', function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, element, attr) {
                var scroll;
                if (scope.$last === true) {
                    $timeout(function () {
                        //Scroll category to top of page after list has completed render
                        scroll = scope.scrollTo(scope.category);
                    });
                }
            }
        };

这给了我一个mysite.com/##grouptitle-2或类似的显示 URL,看起来有点晦涩难懂。有没有办法配置此定位点,使其仅显示一个哈希,或者根本不修改地址栏 URL?

在您的$anchorScroll删除参数。锚滚动将自动从$location.hash(<hash>)中获取哈希

所以你的函数应该看起来像这样:

$scope.categoryHead = "grouptitle-" + location;
$location.hash($scope.categoryHead);
$anchorScroll();

如果 DOM 是动态更新的,则将$location.hash$anchorScroll包装在函数$timeout

执行以下步骤:在此之后$location.hash($scope.categoryHead);加

$anchorScroll();
$location.hash('');
$location.replace();
    

$location.replace() 函数将从 url 中删除"#"。

执行以下步骤:在此之后$location.hash($scope.categoryHead);加

$anchorScroll();
$location.hash('');
$location.replace();

$location.replace() 函数将从 url 中删除"#"。