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:
- Click the first 'add' button - notice the new row immediately below it.
- Click the second 'add' button - notice the new row immediately below it.
- Click the third 'add' button - notice the position is not as expected(?)
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
Error: [ngModel:nonassign] http://errors.angularjs.org/1.4.8/ngModel/nonassign?p0=r.date%20%7CNaNate%3A%20'EEEE'&p1=%3Cinput%20type%3D%22text%22%20ng-model%3D%22r.date%20%7C%date%3A%20'EEEE'%22%20style%3D%22width%3A%20100px%22%20class%3D%22ng-pristine%20ng-untouched%20ng-valid%22%3E). Second, you could usetrack by $indexinstead of the guid: plnkr.co/edit/xq90WZNNlQJ5GFJRXEJb?p=previewidvalue in order to handle duplicate keys, that's whattrack by $indexon theng-repeatis for. also, since thatrow.idis a completely random value, you can't use it as the index to locate the insertion point insplice.3item in the list, if your item has 3 rows (1, 2, 3) and you click3, your new row will be inserted behind3, resulting in1, 2, 3, random). however, if you click1, you get (1, random, 2, 3). now, click3, and you expect it to be the last item ,but it will really be the "fourth" item, giving you (1, random, 2, random, 3). you only notice it when you add1and2first, because of the values you are printing on screen (in that case, you get (1, random, random, random, 2, 3)). Try printing therow.idon screen to see the real order.