Reputation: 321
I have the following app using angular js that's im using to learn it with. I have a table of rows and I want to dynamically add new rows into the table. When I click the add button a new row is created, for some reason on occasions the position is incorrect. Maybe the internal counter for the row is getting messed up but I can't see how or why this is happening..?
Steps to recreate:
I have a plunker available here
https://plnkr.co/edit/WA2K8TNuEE6blNB6zBvZ?p=preview
Can anyone see why this happens? The code that creates the new row is shown below
Row creation code
$scope.addRow = function(row) {
var guid = new Date().getMilliseconds();
var rowDate = row.date;
var rowToAdd = {
id: guid,
date: new Date(rowDate.getFullYear(), rowDate.getMonth(), rowDate.getUTCDay())
};
$scope.rows.splice(row.id, 0, rowToAdd);
};
Any help much appreciated?
Thanks,
P.s if you reverse clicking the 'add' buttons, i.e. you click the third, second then the first 'add' button it works as expected - can't see why this makes a difference - I can guess it's a cursor problem but not sure why..
p.p.s the guid was to get around the angular problem with having duplicate keys restriction within an ng-repeat
Upvotes: 3
Views: 1273
Reputation: 5020
I think you are using the splice()
function wrong. If I understand your problem (I am not sure I do), you need to find the position of the current row, the clicked one, and based on that position insert the new row.
Here's my take on it: https://plnkr.co/edit/xq90WZNNlQJ5GFJRXEJb?p=preview - it still suffers from the problem that clicking on a later day will insert duplicate days, eg. clicking on "Thursday" will insert another "Wednesday". But the positioning is solid.
var index = $scope.rows.indexOf(row);
$scope.rows.splice(index, 0, rowToAdd);
Upvotes: 3