从模态返回数据时 ng-grid 中的范围混乱

2023-12-10

这是笨蛋:http://plnkr.co/edit/aqLnno?p=preview

我有一份人员名单($scope.persons)显示在 ng-grid 中。每行都有一个编辑按钮。当用户单击按钮(ng-click="edit(row)")(见下面的代码),我复制显示的人(angular.copy(row.entity))并打开模式对话框。 ... 到目前为止,一切都很好。

当用户单击模式上的“取消”时,没有任何反应。当用户单击模型上的“保存”时,将返回修改后的人员,并应在其中“重新集成”$scope.persons.

这就是问题开始的地方:我搜索$scope.persons找到正确的人并将其替换为从模式返回的人。日志语句显示$scope.persons修改前后,一切看起来都很好。然而,ng-grid 似乎并不关心。它仍然在不同的(旧的)上运行$scope.persons.

如果我取消注释row.entity = person并直接设置行,ng-grid 中的一切看起来都很好。然而,由于底层数据模型没有正确改变,度假村将再次唤起旧的(未修改的)人。

这是我的编辑功能的代码:

$scope.edit = function(row) {
  $modal.open({
    templateUrl: 'personEdit.html',
    backdrop: true,
    windowClass: 'modal',
    controller: 'PersonModalInstanceCtrl',
    resolve: {
      person: function() {
        return angular.copy(row.entity);
      }
    }
  })
    .result.then(function(person) {
      $log.log('Edited person: ' + JSON.stringify(person));
      angular.forEach($scope.persons, function(p, index) {
        $log.log('p: ' + JSON.stringify(p) + ' index: ' + index);
        if (p.id == row.entity.id) {
          $log.log('scope: ' + JSON.stringify($scope.persons));
          $scope.persons[index] = person;
        }
      });
      $log.log('scope: ' + JSON.stringify($scope.persons));
      // row.entity = person;
    }, function() {});
};

我的示波器做错了什么?

谢谢你的帮助


好的。又学到东西了。 jantimon 的回答为我指明了正确的方向。但我不喜欢他如何更改我的 $scope.persons 数组(我从 RESTful GET 获取此数组,并且喜欢这样的事实:我可以将返回的 JSON 用作 $scope.persons 而不进行修改)。

无论如何,这是解释:

当从原始 $scope.persons 列表复制我的 person 时,我在新的内存位置创建了一个新对象:

angular.copy(row.entity)

这是必要的,因为用户可以“取消”他的编辑。

当用户单击“保存”时,我必须将复制的人员放回 $scope.persons 而不是旧的。我用以下方法做到了这一点:

$scope.persons[index] = person;

尽管这是正确的并且给出了所需的结果(如日志语句所示),但 people[index] 现在指向不同的内存位置。

但是:ng-grid 内部仍然指向旧的内存位置! ng-grid 没有将指针 (person[index]) 记忆为数据模型,而是记住了原始指针 (*person[index]) 的目的地 [抱歉我的 C 语言风格的谈话]。我认为这是 ng-grid 恕我直言的一个错误。

因此,我需要做的就是将新人复制回其来源的完全相同的内存位置。幸运的是,有一个角度指令可以做到这一点:

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

如果你只是替换 $scope.persons[index] = person;与 angular.extend($scope.persons[index], person);一切正常。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从模态返回数据时 ng-grid 中的范围混乱 的相关文章

随机推荐