How to scroll to top of the page in AngularJS?

2020-05-13 20:42发布

I want to scroll to the top of the page after getting an ajax call response using angularjs. Basically, I am displaying alert messages on top of the page and I want to focus the alert message as the ajax response received.

Thanks

5条回答
三岁会撩人
2楼-- · 2020-05-13 20:55

You can use

$window.scrollTo(x, y);

where x is the pixel along the horizontal axis and y is the pixel along the vertical axis.

  1. Scroll to top

    $window.scrollTo(0, 0);
    
  2. Focus on element

    $window.scrollTo(0, angular.element('put here your element').offsetTop);   
    

Example

Update:

Also you can use $anchorScroll

Example

查看更多
欢心
3楼-- · 2020-05-13 21:01

Ideally we should do it from either controller or directive as per applicable. Use $anchorScroll, $location as dependency injection.

Then call this two method as

$location.hash('scrollToDivID');
$anchorScroll();

Here scrollToDivID is the id where you want to scroll.

Assumed you want to navigate to a error message div as

<div id='scrollToDivID'>Your Error Message</div>

For more information please see this documentation

查看更多
▲ chillily
4楼-- · 2020-05-13 21:05

You can use $anchorScroll.

Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

查看更多
在下西门庆
5楼-- · 2020-05-13 21:19

Don't forget you can also use pure JavaScript to deal with this situation, using:

window.scrollTo(x-coord, y-coord);
查看更多
男人必须洒脱
6楼-- · 2020-05-13 21:19

use: $anchorScroll();

with $anchorScroll property

查看更多
登录 后发表回答