嗨,我正在用 angularjs 构建一个聊天应用程序,我希望聊天框自动向下滚动。我正在使用我放入指令的这个示例:http://jsfiddle.net/atRkJ/
它可以正常工作,但是当我将它与 ng-repeat 一起使用时,它不起作用。
html 文件
<ul id="chat" style="height:300px; overflow:auto" scroll-if>
<li data-ng-repeat="messageinfo in messages" >
<div class="message-date">
{{messageinfo[0]}}
</div>
</li>
</ul>
指令.js
.directive('scrollIf', function() {
return{
restrict: "A",
link: function(scope, element, attributes) {
var chat_height = $('#chat').outerHeight();
console.log(chat_height);
$('#chat').scrollTop(chat_height);
}
}
});
有什么帮助吗?谢谢
最佳答案
当你调用代码时:
var chat_height = $('#chat').outerHeight();
console.log(chat_height);
$('#chat').scrollTop(chat_height);
您的ng-repeat 尚未运行并完成其渲染 => 返回的outerHeight
不正确。
您必须在 ng-repeat
完成时运行代码。为此,您可以定义另一个指令:
.directive('scrollItem',function(){
return{
restrict: "A",
link: function(scope, element, attributes) {
if (scope.$last){ // If this is the last item, trigger an event
scope.$emit("Finished");
}
}
}
});
使用它:
<li data-ng-repeat="messageinfo in messages" scroll-item>
现在可以在 ng-repeat
完成时通知您的 scrollIf
指令
.directive('scrollIf', function() {
return{
restrict: "A",
link: function(scope, element, attributes) {
scope.$on("Finished",function(){ //Handle an event when all the items are rendered with ng-repeat
var chat_height = element.outerHeight();
console.log(chat_height);
element.scrollTop(chat_height);
});
}
}
});
关于javascript - 自动滚动 AngularJS 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885969/