64

I've just upgraded to ui-router 0.2.8 from 0.2.0 and I've noticed that when the state changes, the scroll position jumps to the top of te child ui-view that is the subject of the new state.

This is fine but I have two problems with it:

1) I have 30px padding between the top of the page and the ui-view and I would like it to scroll to the top of the page, leaving a gap. At the moment it goes exactly to the top of the ui-view which looks ugly. To achieve this I guess I either need to know how to get it to scroll to the top of the div that the ui-view is in (not the browser viewport), or I need to find out how to override $uiViewScroll to scroll to the ui-view minus 30px.

I have tried $uiViewScrollProvider.useAnchorScroll(); but if I do that it doesn't scroll at all. I have also tried <ui-view autoscroll="false">;, which also stops the scrolling completely.

2) It doesn't actually scroll at the moment, just jumps. Is it suppose to scroll or is it up to the developer to do this with CSS transitions?

Any help would really be appreciated :)

roland
  • 7,695
  • 6
  • 46
  • 61
jonhobbs
  • 26,684
  • 35
  • 115
  • 170

10 Answers10

52

Another approach is to decorate the default $uiViewScroll service, effectively overriding the default behaviour.

app.config(function ($provide) {
  $provide.decorator('$uiViewScroll', function ($delegate) {
    return function (uiViewElement) {
      // var top = uiViewElement.getBoundingClientRect().top;
      // window.scrollTo(0, (top - 30));
      // Or some other custom behaviour...
    }; 
  });
});

And as Hubrus mentioned, for any <ui-view> you do not wish this to apply for, simply add autoscroll="false". I haven't taken a good look into the actual scrolling implementation, I just figured I'd mention the decorator way (it's alot of fun) as an alternative. I'm sure you can work out the exact scrolling behaviour.

  • Thanks, now that I have access to the uiViewElement I guess I could access attributes to see if i've added (for example) elementToScrollTo="main-body" etc ? – jonhobbs Mar 20 '14 at 12:02
  • I would assume so, it's not something I've attempted myself but it sounds feasible. I've only ever used this to null-ify the default scrolling behaviour as it just doesn't fly well with me :) Do let me know if it works out, would be interesting to know of any 'kinks' with this approach. Good luck! –  Mar 20 '14 at 12:04
  • @jonhobbs were either of you able to get this solution working? I attempted it yet it did not solve the problem – mcranston18 May 06 '14 at 21:04
  • I tried but it was complicated. Not very neat but in the end I just put this in the view's controller --- /* Scroll to top of page */ $scope.$watchCollection('stateParams', function(){ $(".mainLayout-body").animate({ scrollTop: 0 }, 300); }); – jonhobbs May 07 '14 at 00:00
  • 3
    @jonhobbs If you're OK with each state going to the top of the page, I'd recommend using $rootScope.$on('$stateChangeStart', function() { $window.scollTo(0,0) }); rather than performing a watch collection on the $stateParams. – mcranston18 May 12 '14 at 15:31
  • 1
    the `uiViewElement` is returned as an array. I was able to get this working by: `var top = uiViewElement[0].getBoundingClientRect().top;` – Phil Dec 10 '14 at 20:37
  • 1
    Note that you cannot scroll to a position other than 0 if there is no scroll bar. You should therefore wrap the call to `scrollTo()` in a `$timeout`. This is also how it is done in the original implementation. – trkoch Dec 15 '14 at 17:14
41

when ever the path changes the router broadcasts an event: $stateChangeSuccess i.e. the url has changed so just listen to it and use jquery to scroll to the top of the page

$rootScope.$on('$stateChangeSuccess',function(){
    $("html, body").animate({ scrollTop: 0 }, 200);
})

place the above code inside

yourAppName.run(function(){

    //the above code here
 })
Rishul Matta
  • 3,383
  • 5
  • 23
  • 29
  • That sounds like like a good suggestion, although it's a scrollable div that I need to go to the top of, not the BODY tag, I'm sure I can work that out. Is it possible to make it so that I could override that for certain views though, so that I can elect not to scroll to the top (for example on a tabset half way down the page). – jonhobbs Mar 15 '14 at 18:23
  • 1
    I found the answer, I used your jquery code but instead of putting it in $stateChangeSucess I put it in the controller for individual views. That way I can decide which views to include it in. – jonhobbs Mar 16 '14 at 01:42
  • yes, putting that in controllers is also an option glad that works! – Rishul Matta Mar 16 '14 at 03:18
  • 11
    Using jquery?? Should really be possible without resorting to jQuery – Spock Mar 17 '14 at 14:00
  • 1
    using jquery is safe in this case thats what i feel because ui view will be inside the body tag and 100% of the times boy tag will be present in the dom its just the templates which will keep on changing inside the body tag. So i felt safe to use it! :) – Rishul Matta Mar 17 '14 at 14:11
  • A couple of answers work but this is the most elegant and correct imo, thank you – Eamon Jun 24 '15 at 23:39
  • 2
    @Spock If you're OK without the animation you can just use `window.scrollTo(0, 0)`. – Casey Sep 08 '15 at 14:52
12

So I had this same problem. I have a fixed-top nav bar. If I put autoscroll="true" in the ui-view it would scroll to the top minus the height of the height of the scroll bar.

So I got rid of the style that added the padding to the body for the top navbar

// fixed navigation at top
//body { padding-top: 100px; }

And applied it to the ui-view

[ui-view=main] {
    padding-top: 100px;
}

Now autoscroll="true" works as expected.

Martin
  • 15,820
  • 4
  • 47
  • 56
7

1) I think the easiest way it to put autoscroll="false" on the ui-view and manipulate the scrolling in the $viewContentLoaded event.

2) This is the browser's default behavior on anchors

VladN
  • 729
  • 1
  • 10
  • 29
  • I can probably write the scrolling code, but not sure where in my code to hook in to the $viewContentLoaded (which I didn't actually know existed) – jonhobbs Mar 14 '14 at 19:59
5

Since $stateChangeSuccess seems not to be available anymore in current AngularJS (as 1.2.x) I changed Rishul Mattas example to the following which works fine for me:

app.run(function ($rootScope) {
  $rootScope.$on('$viewContentLoaded',function(){
    jQuery('html, body').animate({ scrollTop: 0 }, 200);
  });
});
hoeni
  • 3,031
  • 30
  • 45
2

Place on top

<div id="top">.....

Code to scroll:

$rootScope.$on('$stateChangeStart', function() {
    $anchorScroll('top');
});
1

If one combines Angular + Material Design, this is also required to scroll to top:

app.run(function ($rootScope) {
    $rootScope.$on('$viewContentLoaded', function () {
        $("md-content").animate({ scrollTop: 0 }, "fast"); /* <------- Notice this line */
        jQuery('html, body').animate({ scrollTop: 0 }, 200);
    });
});
Elya Livshitz
  • 404
  • 1
  • 6
  • 9
1

I think that we don't need scrolling to top if navigating state is child state, so I wrote this:

$rootScope.$on('$stateChangeSuccess',function(_, _, _, os){
    if(!$state.includes(os) || $state.is(os))
        $("html, body").animate({ scrollTop: 0 }, 200);
});
karaxuna
  • 26,752
  • 13
  • 82
  • 117
0

Most of the time it's not enough just to scroll to the top of the page. It is always a good idea to respect anchor links and to scroll to the specific place in the loaded content designated by location's hash.

Here's the code I use to implement this strategy:

module.run(function (
  $rootScope,
  $timeout,
  $location,
  $uiViewScroll
) {

  // Scrolling when screen changed.
  $rootScope.$on('$viewContentLoaded', function () {
    $timeout(performAutoScroll, 0);
  });


  function performAutoScroll () {
    var hash = $location.hash();
    var element =
         findDomElement('#' + hash)
      || findDomElement('a[name="' + hash + '"]')
      || angular.element(window.document.body)
    ;
    $uiViewScroll(element);
  }
});

$viewContentLoaded is an event generated by Angular when content is loaded inside of the ui-view element. Actually, we need to postpone the execution of our code in order to move it to a next digest cycle. That way the content of the view element will be actually placed in the DOM tree, so we can query it. $timeout with zero delay trick is used for this purpose.

$uiViewScroll service, provided by UI Router is used to actually do the scrolling. We can pass a jQuery/jqLite element to it and it will scroll to it's top border.

We are getting the currect hash from the $location service and using it to find the proper element inside of the DOM tree. It could be either a element with id attribute or a link with name attribute. In case we can't find an element to scroll to we falling back to a body element (i.e. will scroll to the top of the page).

And the findDomElement is just a syntactic sugar. It defined like this:

/**
 * @param {string} selector
 * @returns {jQuery|null}
 */
function findDomElement (selector) {
  var result = $(selector);
  return (result.length > 0 ? result : null);
}

I hope this approach makes sense and will be useful to someone out there. Cheers!

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
0

If you wanted to do this with views conditionally, you could place this in the controller view like so:

.state('exampleState', {
    url: '/exampleURL',
    controller: 'ExampleCtrl as examplectrl',
    onEnter: function($rootScope) {
            $rootScope.$on('$viewContentLoaded',function(){
            jQuery('html, body').animate({ scrollTop: 0 }, 200);
        });
    }
}).

or optionally which might keep your state.js file cleaner place the above in the controller for given view:

function ExampleCtrl ($scope, $rootScope) {

    $rootScope.$on('$viewContentLoaded',function(){
            jQuery('html, body').animate({ scrollTop: 0 }, 200);
        });
}

Hope this helps someone, please let me know if I'm missing something. I used the latter and works great for me.

alphapilgrim
  • 3,761
  • 8
  • 29
  • 58