JSFiddle - React, Tailwind, and code Playground
HTML
<div data-ng-app='scrollTest' data-ng-controller='myCtrl'>
<h4>Scroll to bottom then click Add Text. Div will scroll back to top</h4>
<div class='myList' data-scroll-to-top='data.items.length'>
<ul>
<li data-ng-repeat='item in data.items'>{{item}}</li>
</ul>
</div>
<button type='button' data-ng-click='addItem()'>Add Text</button>
</div>
CSS
.myList {
position: relative;
padding: 0 5px;
margin: 20px;
height: 100px;
width: 200px;
overflow: auto;
border: 1px solid #333;
}
ul {
margin: 0;
}
button {
margin-left: 20px;
}
JavaScript
var mod = angular.module('scrollTest',[]);
// The service that maintains the data
mod.value('myContent', {
items: ['text7', 'text6', 'text5', 'text4', 'text3', 'text2', 'text1']
});
// Inject myContent service into controller
mod.controller('myCtrl', ['$scope', 'myContent',
function($scope, myContent) {
var i = 8; // crude counter for demo
$scope.data = myContent;
$scope.addItem = function() {
// add to beginning of the list (using unshift instead of push)
$scope.data.items.unshift('text' + i++);
};
}
]);
mod.directive('scrollToTop', function(){
return {
restrict: 'A',
link: function postLink(scope, elem, attrs) {
scope.$watch(attrs.scrollToTop, function() {
elem[0].scrollTop = 0;
});
}
};
});