0

这个 Plunkr演示了我遇到的问题。

我有一个在对话框和它的父页面中都显示的数组。在对话框范围内修改该数组工作得很好,但是当我完全替换数组时,更改只能在对话框范围内看到。这是为什么?

我的代码,以防 Plunkr 吃掉它:

angular.module('app', ['ui.bootstrap'])
  .controller('demoController', function($modal) {
    var vm = this;

    vm.message = 'Binding Problems';
    vm.list = [1,2,3];

    vm.modal = function() {
      $modal.open({
        controller: 'modalController as vm',
        templateUrl: 'modal.html',
        resolve: {
          list: function() {
            return vm.list;
          }
        }
      });
    };
  })
  .controller('modalController', ['$modalInstance', '$scope', 'list',
    function($modalInstance, $scope, list) {
      var vm = this;

      vm.list = list;
      vm.modalText = 'Modal Text';

      vm.cancel = function() {
        $modalInstance.dismiss();
      };
      vm.clear = function() {
        vm.list = []; // This does not propagate to the parent controller...
      };

      vm.add = function() {
        vm.list.push(4); // ...but this does.
      };

    }
  ]);

更新: Plunkr 已更新好的,所以我了解现在发生了什么,但不知道如何在我的代码中修复它。在我的实际代码中,我将数据替换为 AJAX 调用的结果。我想在这种情况下我有几个选择,比如vm.list.length = 0then push()ing 从 AJAX 调用返回的每个项目,但这似乎非常低效。这通常是如何完成的?

4

2 回答 2

3

而不是在方法中重新创建数组,clear()只需清空它:

vm.clear = function() {
    vm.list.length = 0;
};

是工作的小伙伴

于 2014-10-09T14:52:54.707 回答
2

这是因为您正在使用新的数组实例覆盖模态范围内的数组引用值帮助。

  vm.clear = function() {
    vm.list = []; // This does not propagate to the parent controller...
  };

而是清除数组,以便模态控制器的范围仍然保持与父控制器相同的引用:-

 vm.clear = function() {
    vm.list.splice(0, vm.list.length); //or vm.list.length = 0;
  };

演示


根据您的实际问题进行更新:-

如果您真的想共享需要通过覆盖刷新的数据,请从您的父级解析一个对象引用,该引用包含将从模态范围修改的数组。

例子:-

在您的父控制器中:-

  vm.data = {list : [1,2,3];};

并解决为: -

   resolve: {
      data: function() {
        return vm.data;
      }
    }

在你的模式中: -

注入数据并使用它:-

 .controller('modalController', ['$modalInstance', '$scope', 'data',
                       function($modalInstance, $scope, data) {

PLNKR

这将确保两个控制器共享相同的底层对象引用,即使其子属性引用发生更改,您也会看到它在另一侧得到反映。

还有另一种可以将数据从模态传播到容器控制器的方法是使用模态承诺链。

链式模态承诺,可作为属性使用result

 $modal.open({
    controller: 'modalController as vm',
    templateUrl: 'modal.html',
    resolve: {
      list: function() {
        return vm.list;
      }
    }
  }).result.then(function(list){
    vm.list = list; //<-- refresh new list
  });

当您关闭模式时,使用模式关闭并传递数据:-

 vm.cancel = function() {
    $modalInstance.close(vm.list); //<-- Pass data
  };

PLNKR

于 2014-10-09T14:52:56.530 回答