Nei*_*kos 5 javascript angularjs
这可以通过jQuery轻松完成:
var msgs = $(".messages ul")
var scroll = false
if( msgs[0].scrollHeight === (msgs.scrollTop() + msgs.outerHeight() ) )
{
scroll = true
}
$scope.messages.push(data)
if(scroll)
{
setTimeout(function(){
msgs.scrollTop(msgs[0].scrollHeight) // Allow it to update!
},0)
}
Run Code Online (Sandbox Code Playgroud)
为了给出一些上下文,ul是消息的容器,我迭代数组$scope.messages,如果容器滚动到底部,它将坚持到底部.这个实现对我有用.
现在,我最近学会了如何在角度中真正使用jQuery.但我想知道,我将如何在纯AngularJS中实现这样的效果?
您可以创建一个指令,该指令将具有一个变量,当该值变为true时将返回到顶部,并且一旦不在顶部就将其自身设置为false.
如何使用:
<div scroll-to-top="isAtTop">
<li ng-repeat="stuff in items">{{stuff}}
<a ng-click="isAtTop = true">Scroll to Top</a>
</div>
Run Code Online (Sandbox Code Playgroud)
这是一个指令(没有测试,但应该工作):
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;
});
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)