In most cases, this is not enough to scroll to the top of the page. It is always recommended that you refer to anchor links and scroll to a specific place in the loaded content, determined by the location hash.
Here is the code that I use to implement this strategy:
module.run(function ( $rootScope, $timeout, $location, $uiViewScroll ) {
$viewContentLoaded - An event generated by Angular when content is loaded inside a ui-view element. In fact, we need to delay the execution of our code in order to move it to the next digest cycle. Thus, the contents of the view element will actually be placed in the DOM tree, so we can request it. $timeout with a zero-delay trick is used for this purpose.
$uiViewScroll service provided by the UI Router is used for actual scrolling. We can pass the jQuery / jqLite element to it, and it will scroll to the top of it.
We get a personal hash from the $location service and use it to find the correct item inside the DOM tree. This can be either an element with an id attribute or a link with a name attribute. In case we cannot find the element to scroll, we return to the body element (i.e., scroll up the page).
And findDomElement is just syntactic sugar. It is defined as follows:
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. Hurrah!
Slava Fomin II Jul 02 '15 at 16:35 2015-07-02 16:35
source share