Neikos Neikos - 2 months ago 5x
AngularJS Question

How do I scroll a div in angularjs

This is easily done with jQuery:

var msgs = $(".messages ul")

var scroll = false

if( msgs[0].scrollHeight === (msgs.scrollTop() + msgs.outerHeight() ) )

scroll = true



msgs.scrollTop(msgs[0].scrollHeight) // Allow it to update!



To give some context, ul is the container of the messages, I iterate over the array in
and if the container is scrolled to the bottom it will stick to the bottom.
This implementation works for me.

Now, I recently learned how one shouldn't really use jQuery in angular. But I am wondering, how would I achieve something like this in pure AngularJS?


You can create a directive which will have a variable which when true will go to the top, and will set itself to false once not at top anymore.

How to use:

 <div scroll-to-top="isAtTop">
   <li ng-repeat="stuff in items">{{stuff}}
   <a ng-click="isAtTop = true">Scroll to Top</a>

Here's a directive (didn't test, but should work):

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) {
        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;