DEMO
List of objects is rendered using ng-repeat. Suppose that this list is very long and user is scrolling to the bottom to see some objects.
W
Below is an improvement to Arthur's version that prevents scrolling regardless if the added item is added above or below the scroll: JS Bin
angular.module("Demo", [])
.controller("DemoCtrl", function($scope) {
$scope.items = [];
for (var i = 0; i < 10; i++) {
$scope.items[i] = {
id: i,
name: 'item ' + i
};
}
$scope.addNewItemTop = function() {
$scope.items.unshift({
id: $scope.items.length,
name: "item " + $scope.items.length
});
};
$scope.addNewItemMiddle = function() {
$scope.items.splice(5, 0, {
id: $scope.items.length,
name: "item " + $scope.items.length
});
};
$scope.addNewItemBottom = function() {
$scope.items = $scope.items.concat({
id: $scope.items.length,
name: "item " + $scope.items.length
});
};
})
.directive("keepScroll", function(){
return {
controller : function($scope){
var element = 0;
this.setElement = function(el){
element = el;
};
this.addItem = function(item){
console.group("Item");
console.log("OffsetTop: " + item.offsetTop);
console.log("ScrollTop: " + element.scrollTop);
if(item.offsetTop <= element.scrollTop) {
console.log("Adjusting scorlltop position");
element.scrollTop = (element.scrollTop+item.clientHeight+1); //1px for margin
} else {
console.log("Not adjusting scroll");
}
console.groupEnd("Item");
};
},
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]);
}
};
});
.wrapper {
width: 200px;
height: 300px;
border: 1px solid black;
overflow: auto;
/* Required for correct offsetParent */
position: relative;
}
.item {
background-color: #ccc;
height: 100px;
margin-bottom: 1px;
}
JS Bin
{{ item.name }}