nitin nitin - 1 year ago 450
AngularJS Question

Angularjs : Scroll to bottom of div

I'm having trouble scrolling to last message.

var app=angular.module('myApp', ['ngMaterial'] );
app.controller('ChatCtrl', function($window, $anchorScroll){
var self = this;
self.messageWindowHeight = parseInt($window.innerHeight - 170) + 'px';
self.messages = [];
for(var i = 1 ; i<=200;i ++){

self.user = { text : ""};
self.send = function(){
self.user.text = "";

app.directive('scrollToBottom', function($timeout, $window) {
return {
scope: {
scrollToBottom: "="
restrict: 'A',
link: function(scope, element, attr) {
scope.$watchCollection('scrollToBottom', function(newVal) {
if (newVal) {
$timeout(function() {
element[0].scrollTop = element[0].scrollHeight;
}, 0);


/* Styles go here */
.chat-box {
padding: 8px;
border-radius: 8px;
.message-box {
border-top: 1px solid #E0E0E0;
position: fixed;
right: 0;
bottom: 0;
width: 100%;
height: 120px;
background: white;

.message {
overflow: scroll;
margin: 4px;
border: 1px solid #E0E0E0;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
height: 110px;

<!DOCTYPE html>

<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="">
<link rel="stylesheet" href=",400,500,700,400italic">

<body ng-app='myApp' layout="column" layout-fill ng-controller="ChatCtrl as ctrl">
<!-- content starts here -->
<md-toolbar class="md-whiteframe-z2">
<div class="md-toolbar-tools">
<md-content layout="column" style="background-color: #F5F5F5;" ng-style="{'height':ctrl.messageWindowHeight}">
<div class="chat-box">
<ol class="discussion" scroll-to-bottom="ctrl.messages">
<li ng-repeat="message in ctrl.messages track by $index" id="msg-{{$index}}">
<form name="userForm" novalidate ng-submit="ctrl.send()" layout="row" layout-padding layout-align="center center" class="message-box">
<div class="message" flex>
<md-input-container class="md-block">
<input type="text" name="text" ng-model="ctrl.user.text" />
<md-button class="md-icon-button" type="submit">

<!-- content ends here -->

<!-- Angular Material Dependencies -->
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>

<script src="script.js"></script>


Here's a plunk of my code.

Answer Source

Move the scroll-to-bottom directive to the md-content element

 <!-- MOVE directive here -->
 <md-content scroll-to-bottom="ctrl.messages" layout="column" style="background-color: #F5F5F5;" ng-style="{'height':ctrl.messageWindowHeight}">
      <div class="chat-box">
        <!-- NOT HERE
        <ol class="discussion" scroll-to-bottom="ctrl.messages">
        <ol class="discussion">
          <li ng-repeat="message in ctrl.messages track by $index" id="msg-{{$index}}">


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download