I try to implement scroll to the last added entry whithin ngRepeat directive.
I found and investigated some related SO questions: #1, #2. But still can't solve the problem.
The code is pretty simple. When the user adds new record to the array, the controller broadcasts 'scroll-event' with the new added item's name, than the directive receives this event and scroll to the new added entry in the list.
<div ng-controller="MainCtrl">
<input ng-model="newItem" ng-keydown="$event.which === 13 && addNewItem(newItem)"/>
<button ng-click="addNewItem(newItem)">Add</button>
<div id="items-list" scroll-to-new-item>
<div ng-repeat="item in items | orderBy: 'name'">
<input ng-model="item.name" ng-readonly="true"/>
</div>
</div>
</div>
app.controller("MainCtrl", function($scope){
$scope.items = [
{id: 1, name: "aaa"}, {id: 2, name: "bbb"},
{id: 3, name: "ccc"}, {id: 4, name: "ddd"},
.......
];
$scope.addNewItem = function(newItem){
$scope.items.push({name: newItem});
$scope.$broadcast('scroll-event', newItem);
$scope.newItem = "";
};
});
This is my directive, which should scroll to the last added record to the list.
app.directive("scrollToNewItem", function(){
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$on('scroll-event', function (event, newValue) {
if(newValue){
var newItemHeightPosition = // !!! MY ISSUE HERE !!!
$('#items-list').animate({
scrollTop: newItemHeightPosition
}, 'slow');
}
});
}
};
});
But I can't figure out, how to get the new added item's top-height position. I tried several variants, but they didn't get any results. For example the following jquery selectors doesn't work:
$('#items-list').find('input[value=' + newValue +']');
$('#items-list').find('input').eq(newValue);
Please note, that the array is sorted in alphabetical order, so that complicates this task.
Who knows, how to solve this issue?
Thanks in advance!