0

如何配置AngularJs滚动到带有#id的href中指定的锚元素?

问题

带有散列的锚链接,例如。href="#recommanded" 变为 url#/recommanded 而不是 url#recommanded,因此它不会按预期滚动。如果没有加载 angularjs 库,它工作正常。在状态栏中,当我将光标移动到链接顶部时,浏览器的状态栏会正确显示我将要前往的链接,但单击后它将被转换并且无法正确滚动。我没有使用角度的路线。

我的 AngularJS 代码中可能会干扰滚动/js 位置操作的片段:

...
app.config([ '$httpProvider', '$compileProvider', function($httpProvider, $compileProvider) {
    $compileProvider.debugInfoEnabled(false);
    // Initialize get if not there
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }

    // Disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
} ]);
...
app.directive('jumpForm', function($timeout) {
    return {
        restrict : 'A',
        link : function(scope, elem) {

            // set up event handler on the form element
            elem.on('submit', function() {
                $timeout(function() {
                    // find the first invalid element
                    var firstInvalid = elem[0].querySelector('.has-error');

                    // if we find one, set focus
                    if (firstInvalid) {

                        $('html, body').animate({
                            duration : 2000,
                            scrollTop : (firstInvalid.offsetTop + 100)
                        });
                    }
                }, 200);

            });
        }
    };
});
...
app.factory('httpResponseInterceptor', [ '$q', '$location', '$window', function($q, $location, $window) {
    return {
        response : function(response) {
            if (response && response.data && response.data.errorCode == 'AUTHENTICATION_REQUIRED') {
                var _context = $("body").attr("data-context");
                var redirectUrl = _context + '/registration?msg=session_expired';
                $window.location.href = redirectUrl;
                return $q.reject(response);
            }
            return response;
        }
    }
} ]);

app.config([ '$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('httpResponseInterceptor');
} ]);

带有标签的电话:

<a href="#recommanded"> </a>

试验和错误

内部解决方法

锚滚动

在线程如何处理 AngularJS 中的锚散列链接中,建议插入以下代码段:

app.controller('TestCtrl', function($scope, $location, $anchorScroll) {
    $scope.scrollTo = function(id) {
        $location.hash(id);
        $anchorScroll();
    }
});

在调用它时:

<a ng-click="scrollTo('recommanded')">Foo</a>

这导致控制台上没有错误,但与以前的行为相同。网址被转换为没有滚动到锚点。此外,我不喜欢最终为此拥有 ng-click 功能的想法。

附加我的angularjs:

app.run(function($rootScope, $location, $anchorScroll) {
    //when the route is changed scroll to the proper element.
    $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) 
    {
        if($location.hash()) $anchorScroll();  
    });
});

并将其称为

<a href="#/test#recommanded">Test/Foo</a>

结果没有错误,但滚动也不起作用。

有些人暗示只在href 中做一个#/#recommanded。使用目标 =“_self”。他们都不适合我。

外部解决方案

指令滚动到

   app.directive('scrollto',
   function ($anchorScroll,$location) {
        return {
            link: function (scope, element, attrs) {
                element.click(function (e) {
                    e.preventDefault();
                    $location.hash(attrs["scrollto"]);
                    $anchorScroll();
                });
            }
        };
})

html看起来像:

<a href="" scrollTo="recommanded">link</a>

这个确实有效,但更喜欢调用 href="#recommended" 的解决方案。或者至少为滚动设置动画。

angular-scroll 的 du-smooth-scroll

在我的 angularApp.js 中添加了duScrollvar app = angular.module('app', [ ..., 'duScroll' ]); 我在 angularApp.js 页面上加载了 angular-scroll.min.js 文件,没有错误。我要求<a du-smooth-scroll href="#recommended-to-you">recommanded</a>一个具有该 ID 的现有 div。但它不会做任何事情,没有js错误但不会移动。尝试了添加显式缓动持续时间等设置的 duScroll 模块,没有错误但无法正常工作。

4

1 回答 1

0

html5模式

在 url 中的散列之前添加斜杠中所述,我尝试通过添加以下内容来打开 html5 模式:

app.config(function($locationProvider) {
          $locationProvider.html5Mode(true);
        })

我已经在 head 部分设置了基本标签。

这些设置使它按预期开始工作。

...但我会提到,一旦地址栏中的位置更新为引用的哈希,如果我再次单击链接,它就会下降一点,而不是引用的位置。单击具有不同锚点的链接效果很好。不确定这是一般错误还是我的一些设置适得其反。

于 2018-01-30T12:36:21.127 回答