问题
I did not like the answer to this question. To my mind, it has a bad code smell.
I am new to Angular, so I thought I could learn something if I created a Plunk to help that questioner.
My Plunk is http://plnkr.co/edit/fJcew7cGCPzJ0nhIQXjg?p=preview, but there two things which I don't understand.
Please note that I assigned the ng-grid's data two ways - at one fell stroke and row by row. Comment one out & uncomment the other to play around with it.
And be sure to press F12 to see the developer's console log messages.
1) why am I getting TWO ngGridEventData events?
2) why, when I push() row by row am I not getting one ngGridEventData event per push() ? I am trying to implement master/detail/even more detailed with 3 grids (nothing to do with the current question) and have been googling for a few days now. Many people seem believe that they will get multiple ngGridEventData events and want to know ho to detect that the grid is fully rendered (hence the check in my Plunk).
In short, can anyone explain in detail how ngGridEventData works? Thanks; your answer will help a lot of people.
回答1:
In a recent Answer here I showed some learnings about this strange behavior. It seems that this routine is called 2 times for reasons I can't really understand (caching maybe?).
You can get this to work if you only react when the data-object is a clone:
if (data.selected === true) {
if (data.isClone) {
numSelectionChanges = numSelectionChanges + 1;
console.log("afterSelectionChange", 'Selection has chanegd ' + numSelectionChanges + ' times');
console.table(data);
}
}
Give it a try, and if you find out why this happens please let me know.
More findings update:
Have a look at this Plunker
I have included the ng-grid.js script directly in the plunker. If you look at rows 3344-3349 you will find this piece of code:
$scope.$on('$destroy', $scope.$parent.$watch(options.data, dataWatcher));
$scope.$on('$destroy', $scope.$parent.$watch(options.data + '.length', function() {
dataWatcher($scope.$eval(options.data));
$scope.adjustScrollTop(grid.$viewport.scrollTop(), true);
}));
As you can see the there are two watchers applied which looks like a leftover from changes to me. (Although i'm not sure, with me being dumb and those guys being clever). However, if I comment the first line out everything seems to work as expected.
Be carefull when you try this out, because it may break other functionality. I'm not very comfortable with hacking in such a lengthy source code. If someone who is an actual ng-grid team member sees this he can tell me if I found a bug and how to report it. (Never done that before!)
来源:https://stackoverflow.com/questions/23419722/ng-grid-why-is-afterselectionchange-called-twice