angularjs - AngularUI Router - scroll to element on state change -


i have searched on stackoverflow last 5 hours , none of related answers quite solve problem. have ui-router state loads long list of messages generated custom directive. page linked in many places pointing different message. want scroll selected message.

i can work using $anchorscroll if surround call $timeout. $timeout(function(){$anchorscroll()};) if $timeout not there call $anchorscroll nothing since view has not loaded.

here of relevant code.

<message id='message{{message.id}}'    ng-repeat='message in messages'    message='message'    ng-class="{'current':current == 'message{{message.id}}'}" > </message> 

in controller set current $scope.current = $location.hash(). works.

if load page #/messages#message100 directly page correctly scroll. however, if different view use link such this:

<button ui-sref="message-state({'#':'message{{message.id}}'})>   go message {{message.id}} </button> 

the page not automatically scroll correct anchor since message list has not been made yet. putting call $anchorscroll() in $timeout can make page scroll.

i don't using $timeout purpose. know not supposed manipulate dom in controller this.

i have tried registering call $anchorscroll() many of $stateprovider events such as:

$state.$on('$viewcontentloaded', function(event) {   $anchorscroll(); }); 

but @ time $viewcontentloaded fires message list not exist in dom , page not scroll.

iwhat best way make ui-router scroll based on $location.hash().

even facing similar situation , after days of try , error, came this.

in ui router add id parameter state on want enable scroll.

$stateprovider.state('index', {     url: '/',     params: {         id: null     } }) 

then in html use ui-sref

<li><a ui-sref="index({id: 'about-us'})"  >about us</a></li> 

at last in app.run module detect state change using

$rootscope.$on('$viewcontentloaded', function(event){     if ($state.current.name == 'index') {         if($stateparams.id) {             $anchorscroll.yoffset = 150;             $location.hash($stateparams.id);             $timeout(function(){$anchorscroll()}, 1000);         }     } }); 

hope helps. plunkr if needed.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -