retain scroll position

SO: 23736647, retain scroll position when new item is added to repeat list

by Mayank Dixit

HTML

<div ng-init ng-controller="mainCtrl"  class="maindiv" keep-scroll>
    <div ng-repeat="el in list" scroll-item>{{el}}</div>
</div>

CSS

.maindiv {
    width: 200px;
    height: 300px;
    background: lightgray;
    border: 1px solid;
    color: black;
    font-size: 40px;
    overflow: auto;
}

JavaScript

angular.module("myApp", [])
.controller("mainCtrl", function($scope, $window) {
    $scope.list = [
                  "one",
                  "two",
                  "three",
                  "four",
                  "five",
                  "six",
                  "seven",
                  "eight",
                  "nine",
                  "ten",
                  "eleven",
                  "twelve",
                  "thirteen",
                  "forteen",
                  "fifteen",
                  "sixteen",
                  "seventeen",
                  "eighteen",
                   ];
        $window.setTimeout(function(){$scope.list.unshift("mayank"); $scope.$apply();}, 3000)
})
        
.directive("keepScroll", function(){

  return {

    controller : function($scope){
      var element = null;

      this.setElement = function(el){
        element = el;
      }

      this.addItem = function(item){
        console.log("Adding item", item, item.clientHeight);
        element.scrollTop = (element.scrollTop+item.clientHeight+1);
       //1px for margin from your css (surely it would be possible
       // to make it more generic, rather then hard-coding the value)
      };

    },

    link : function(scope,el,attr, ctrl) {

     ctrl.setElement(el[0]);

    }

  };

})

.directive("scrollItem", function(){

  return{
    require : "^keepScroll",
    link : function(scope, el, att, scrCtrl){
      scrCtrl.addItem(el[0]);
    }
  }
})