Scope confusion in ng-grid when returning data from modal

牧云@^-^@ 提交于 2019-12-02 01:21:22

OK. Again something learnt. The answer of jantimon pointed me in the right direction. But I didn't like how he changed my $scope.persons array (I get this array from a RESTful GET and liked the fact that I can just use the returned JSON as $scope.persons without modification).

Anyway, here is the explanation:

When copying my person from the original $scope.persons list I created a new object in a new memory location:

angular.copy(row.entity)

This is necessary as the user can "Cancel" his edit.

When the user clicks "Save" I have to take this copied person and put it back to $scope.persons instead of the old one. I did this with:

$scope.persons[index] = person;

Although this is correct and gives the desired result (as the log statements show), the persons[index] now points to a different memory location.

BUT: ng-grid internally still points to the old memory location! ng-grid has not memorized the pointer (person[index]) as the data model but instead has memorized the destination of the original pointer (*person[index]) [sorry for my C-stylish talking]. I would consider this a BUG in ng-grid IMHO.

So all I need to do is copy the new person back to the exact same memory location it has come from. Luckily, there is an angular directive for that:

angular.extend($scope.persons[index], person);

If you just replace $scope.persons[index] = person; with angular.extend($scope.persons[index], person); everything works fine.

Looks like ng-grid isn't updating correctly when you are changing the array

You might keep the pointer of the row entity like in this example here: http://plnkr.co/edit/0lDoKOg4kXXa51NlSuMg?p=preview

It uses $scope.persons[index].data = person.data; instead of $scope.persons[index] = person;.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!