1

I am using ui-router and i am trying to scroll automatically in the controller. However anchorScroll seems to do nothing, my guess is that it doesn't like two # in the URL.

Example:

index.php#/initiative/1/commentscroll/4

turns into:

index.php#/initiative/1/commentscroll/4#comment-id-4

But the scrolling isn't done (and yes the anchors actually exist ;)

Any ideas?

controllersModule.controller('InitiativeController', ['$http','$timeout','$location','$state','services','$stateParams','$anchorScroll', function($http,$timeout,$location,$state,services,$stateParams,$anchorScroll){
var pk = this;
pk.initiative={};

if($state.current.url.indexOf("/commentscroll/")!=1){
    $timeout(function() {
        $location.hash('comment-id-'+$stateParams.commentId);
        $anchorScroll();
    });
}


services.get($stateParams.initiativeId,'initiative','').then(function(data){
    pk.initiative=data;

});

function fillScrollId(element,index,array){
    if(element.initiative_comment_id===$stateParams.commentId){
        element.scrollToMe="yes";
    }
    if(element.comments.length>0){
        element.comments.forEach(fillScrollId);
    }
}
}]);

2 Answers 2

2

I fixed it, it was a 'timing' problem..

$location.hash('comment-id-'+$stateParams.commentId);
$timeout(function(){$anchorScroll()}, 800);

The $timeout does the trick!

Sign up to request clarification or add additional context in comments.

Comments

1

Alternative (animated) solution without $anchorScroll

$timeout(function () {
    if ($location.hash()) {
        var anchor = 'a[name="' + $location.hash() + '"]';
        if ($(anchor)) {
            $('html,body').animate({ scrollTop: ($(anchor).offset().top) + 0 }, 'slow');
        }
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.