I am attempting to implement scrolling to the last added entry within an ngRepeat directive.
After researching related questions on Stack Overflow, such as #1 and #2, I still cannot find a solution to my problem.
The code is straightforward. When a user adds a new record to the array, the controller sends a 'scroll-event' with the name of the newly added item. The directive then listens for this event and scrolls to the new 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 that should scroll to the last added record in 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');
}
});
}
};
});
However, I am struggling to determine how to retrieve the top-height position of the newly added item. Various attempts using jQuery selectors have not been successful:
$('#items-list').find('input[value=' + newValue +']');
$('#items-list').find('input').eq(newValue);
It is important to note that the array is sorted alphabetically, adding complexity to this task.
If anyone has insight on how to resolve this issue, I would greatly appreciate it.
Thank you in advance!