简体   繁体   English

角度切换状态后,平滑滚动到元素

[英]Smooth scroll to an element after switching state in angular

I am developing in Angular using a node package for smooth scrolling. 我正在使用节点包进行平滑滚动的Angular开发。 I have a navbar on all my pages (as a directive) and if someone is on my history state /history and clicks on a link in the navbar to go to a specific section on the homepage / , I want the site to switch states to the homepage state and then to scroll automatically to the section that the user clicked on in the navbar. 我有我的所有页面的导航栏(作为指令),如果有人在我的历史状态/history在导航栏的链接,并点击进入主页上的一个特定部分/ ,我希望自己的网站切换状态,以主页状态,然后自动滚动到导航栏中用户单击的部分。

Right now I'm doing 现在我在做

    scope.goToSection = function (val, state) {
        $state.go(state)
        setTimeout(function() {smoothScroll(document.querySelector(val))}, 100);
    }

which is working but I am not sure if this is the most natural way to get this functionality. 这是可行的,但我不确定这是否是获得此功能的最自然方法。

I tried $state.go(state).then(smoothScroll(document.querySelector(val))); 我尝试了$state.go(state).then(smoothScroll(document.querySelector(val))); but the page would not scroll after switching states. 但切换状态后页面将不会滚动。 Is there a better or more natural way to get this functionality? 是否有更好或更自然的方法来获得此功能?

The problem with custom functions used to switch states instead of ui-sref is that you lose for example the posibility to click with the mouse wheel to open in the new tab etc. 用于切换状态而不是ui-sref的自定义函数的问题是,例如,您失去了用鼠标滚轮单击以在新选项卡中打开等的可能性。

Solution to this would be to check $stateChangeSuccess event and scroll based on the data passed to the new state. 解决方案是检查$ stateChangeSuccess事件,然后根据传递给新状态的数据进行滚动。

    $rootScope.$on('$stateChangeSuccess', function(e, toState, toParams) {
        // do the scrolling

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM