简体   繁体   中英

Smooth scroll to an element after switching state in angular

I am developing in Angular using a node package for smooth scrolling. 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.

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))); 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.

Solution to this would be to check $stateChangeSuccess event and scroll based on the data passed to the new state.

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

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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