您可以创建一个指令,该指令将具有一个变量,当它为 true 时将转到顶部,并且一旦不再位于顶部,它就会将自身设置为 false。
如何使用:
<div scroll-to-top="isAtTop">
<li ng-repeat="stuff in items">{{stuff}}
<a ng-click="isAtTop = true">Scroll to Top</a>
</div>
这是一个指令(没有测试,但应该可以):
angular.module('myApp').directive('scrollToTop', function() {
return {
restrict: 'A',
link: function(scope, elm, attr) {
var isTop;
//bind changes from scope to our view: set isTop variable
//depending on what scope variable is. If scope value
//changes to true and we aren't at top, go to top
scope.$watch(attr.scrollToTop, function(newValue) {
newValue = !!newValue; //to boolean
if (!isTop && newValue) {
elm[0].scrollTo(0,0);
}
isTop = newValue;
});
//If we are at top and we scroll down, set isTop and
//our variable on scope to false.
elm.bind('scroll', function() {
if (elm[0].scrollTop !==0 && isTop) {
//Use $apply to tell angular
//'hey, we are gonna change something from outside angular'
scope.$apply(function() {
//(we should use $parse service here, but simple for example)
scope[attr.scrollTop] = false;
isTop = false;
});
}
});
}
};
});