Reputation: 3301
Hi I'm building a chatapp in angularjs and I want the chatbox to scroll down automatically. I'm using this example that I put in a directive: http://jsfiddle.net/atRkJ/
It works as it is but when I use it with a ng-repeat it doesn't work.
html file
<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>
directive.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);
}
}
});
Any help? Thanks
Upvotes: 2
Views: 3169
Reputation: 48992
When you call the code:
var chat_height = $('#chat').outerHeight();
console.log(chat_height);
$('#chat').scrollTop(chat_height);
Your ng-repeat does not run and finish its rendering yet => the outerHeight
returned is not correct.
You must run your code when the ng-repeat
finishes. To do it, you could define another directive:
.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");
}
}
}
});
Use it:
<li data-ng-repeat="messageinfo in messages" scroll-item>
Your scrollIf
directive can now be notified when the ng-repeat
completes
.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);
});
}
}
});
Upvotes: 4